Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Timer.periodic() is great to have a function repeatedly execute, but is it possible to have the the timer cancel itself if an arbitrary condition is reached outside the function being executed by the timer?

like image 727
Matt S. Avatar asked Mar 03 '18 18:03

Matt S.


People also ask

How do you stop periodic timer on flutter?

Creating a restartable timer in Flutter As we saw above, we can cancel Timer by calling the cancel() method.

What is a periodic timer?

A periodic timer is one that goes off periodically, notifying the thread (over and over again) that a certain time interval has elapsed. A one-shot timer is one that goes off just once.


1 Answers

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.

like image 63
Günter Zöchbauer Avatar answered Sep 18 '22 18:09

Günter Zöchbauer