ExpiringPeriodicTimer constructor

ExpiringPeriodicTimer({
  1. required Duration total,
  2. required Duration interval,
  3. required void onTick(
    1. Duration timeLeft
    ),
  4. void onFinish()?,
})

Constructor.

The ExpiringPeriodicTimer will expire after the total amount of time has elapsed. The optional onFinish callback will be invoked upon expiration.

Until the timer expires, onTick will be invoked periodically every interval with the amount of time left before expiration.

Implementation

ExpiringPeriodicTimer({
  required Duration total,
  required Duration interval,
  required void Function(Duration timeLeft) onTick,
  void Function()? onFinish,
})  : _endTime = clock.now().add(total),
      _interval = interval,
      _onTick = onTick,
      _onFinish = onFinish {
  // Schedule the periodic [Timer] first to try to ensure that it fires first
  // if it coincides with the completion [Timer].
  _periodicTimer = Timer.periodic(_interval, (_) {
    _onTick(_endTime.difference(clock.now()));
  });
  _completionTimer = Timer(total, () {
    _periodicTimer.cancel();
    _onFinish?.call();
  });
}