flushTimers method
Elapses time until there are no more active timers.
If flushPeriodicTimers
is true
(the default), this will repeatedly run
periodic timers until they're explicitly canceled. Otherwise, this will
stop when the only active timers are periodic.
The timeout
controls how much fake time may elapse before a StateError
is thrown. This ensures that a periodic timer doesn't cause this method to
deadlock. It defaults to one hour.
Implementation
void flushTimers({
Duration timeout = const Duration(hours: 1),
bool flushPeriodicTimers = true,
}) {
final absoluteTimeout = _elapsed + timeout;
_fireTimersWhile((timer) {
if (timer._nextCall > absoluteTimeout) {
// TODO(nweiz): Make this a [TimeoutException].
throw StateError('Exceeded timeout $timeout while flushing timers');
}
// Always run timer if it's due.
if (timer._nextCall <= elapsed) return true;
// If no timers are due, continue running timers
// (and advancing time to their next due time)
// if flushing periodic timers,
// or if there is any non-periodic timer left.
return flushPeriodicTimers || _timers.any((timer) => !timer.isPeriodic);
});
}