How to make Timer.periodic cancel itself when a condition is reached?

You get the timer passed into the callback. You can just call cancel() on it:

Timer.periodic(const Duration(seconds: 1), (timer) {
  if(condition) {
    timer.cancel();
  }
});

or

Timer timer;

startTimer() {
  timer = Timer.periodic(const Duration(seconds: 1), (timer) {
    if(condition) {
      cancelTimer();
    }
  });
}

cancelTimer() {
  timer.cancel();
}

this way the timer can be cancelled independent of a timer event.

Full non-nullable Dart example

import 'dart:async';

Timer? timer;
bool condition = false;

void main() async {
  startTimer();

  await Future.delayed(const Duration(milliseconds: 600), () => condition = true);
}

startTimer() {
  timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
    print("condition: ${condition}");
    if (condition) {
      cancelTimer();
    }
  });
}

cancelTimer() {
  timer?.cancel();
  timer = null;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)