run method

void run(
  1. AsyncAction action
)

Schedules action to run after delay. In immediate mode, the first call executes right away while subsequent calls during that burst are debounced (no trailing execution occurs until a new burst starts).

Throws a StateError if the debouncer has been disposed.

Implementation

void run(AsyncAction action) {
  _ensureNotDisposed();
  if (_isPaused) {
    // If paused, store the action and timestamp without scheduling timers.
    _lastAction = action;
    _lastCallTime = DateTime.now();
    _logDebug('Debouncer is paused. Action stored for later execution.');
    _publishState();
    return;
  }

  _lastAction = action;
  final now = DateTime.now();
  _lastCallTime = now;
  final isNewBurst = _firstCallTime == null;
  _firstCallTime ??= now;

  // Leading edge for immediate mode is only triggered for a new burst.
  if (_immediate && isNewBurst) {
    _executeAction(action);
  }

  // Cancel only the trailing timer to keep maxWait tracking intact.
  if (_timer?.isActive ?? false) {
    _timer!.cancel();
  }
  _timer = null;

  // Always schedule a trailing timer to close the burst after inactivity.
  _timer = _timerFactory(_delay, () {
    if (!_immediate && _lastAction != null) {
      _executeAction(_lastAction!);
    }
    _cancelTimers();
  });

  // Set up a maxWait timer if specified.
  if (_maxWait != null && _maxWaitTimer == null) {
    _maxWaitTimer = _timerFactory(_maxWait, () {
      if (_lastAction != null) {
        _executeAction(_lastAction!);
      }
      _cancelTimers();
    });
  }

  _logDebug('Scheduled action.');
  _publishState();
}