Rory Davis
Rory Davis

Reputation: 5

Multiple timers starting at once (Flutter)

So I have created a timer that I can start and stop with a button. Mostly works fine, however if I spam the button to start and stop it really fast, it seems to start multiple timers at once and as a result, the function gets fired a lot faster than one second. Is there anyway that I can keep it at one timer at a time or some sort of way to cancel all the timers at once (I am very new to flutter and timers).

to start the timer:

void startTimer() {
    Timer.periodic(Duration(seconds: seconds), (t) {
      setState(() {
        timer = t;
        randomNote = Random().nextInt(6);
        randomType = Random().nextInt(6);
      });
    });
  }

to stop the timer:

timer?.cancel();

I have tried adding an if statement to check if a timer is active so the code looks like this:

 void startTimer() {
    if (timer?.isActive != true) {
      Timer.periodic(Duration(seconds: seconds), (t) {
        setState(() {
          timer = t;
          randomNote = Random().nextInt(6);
          randomType = Random().nextInt(6);
        })
      });
    }
  }

But nothing changes.

Upvotes: 0

Views: 1205

Answers (2)

Shaan Mephobic
Shaan Mephobic

Reputation: 1216

Well since you say if (timer?.isActive != true) isn't working, an alternative to that is this,

bool isTimerOn = false;
...
void startTimer() {
  if(!isTimerOn){ 
    isTimerOn = true;
    Timer.periodic(Duration(seconds: seconds), (t) {
      setState(() {
        timer = t;
        randomNote = Random().nextInt(6);
        randomType = Random().nextInt(6);
      });
    });
  }
}

And if you're going to do timer?.cancel(); make sure to set isTimerOn as false.

Upvotes: 0

Monik
Monik

Reputation: 321

You can check if any timer is currently working or not. If there is some timer going on, just don't let the function to be triggered. To check if timer is working, you can look over here

Upvotes: 0

Related Questions