call method

void call(
  1. void action()
)

Executes action only if enough time has passed since the last execution.

The action runs immediately if:

  • This is the first call
  • More than interval has elapsed since the last execution

Otherwise, the action is skipped.

Example:

final throttle = Throttle(Duration(seconds: 1));

throttle(() => print('1')); // Executes immediately
throttle(() => print('2')); // Skipped (< 1 second)
throttle(() => print('3')); // Skipped (< 1 second)
// ... wait 1+ seconds
throttle(() => print('4')); // Executes (interval passed)

Implementation

void call(void Function() action) {
  final now = DateTime.now();
  final lastRun = _lastRun;
  if (lastRun == null || now.difference(lastRun) > interval) {
    _lastRun = now;
    action();
  }
}