Flutter timer.periodic is slower than real life

874 Views Asked by At

I am using timer.periodic to call some functions at different times. The problem which I am facing is that the timer is much slower than real life like for example what you will see in my code that the timer should finish in 5 seconds but in real life its taking 25 seconds to finish.

 void startTheTimer(){
    var counter = 5;
    final zeroDurationTimer = Timer.run(() {
      _StartDataCollection();
    });
    Timer.periodic(const Duration(seconds: 5), (timer) {
      print(timer.tick);
      counter--;
      if (counter == 2) {
        _StopDataCollection();
      }else if (counter == 1){
        createUser();
      }
      if (counter == 0) {
        print('Cancel timer');
        timer.cancel();
        print(numbers.length);
        print(fifo.length);
      }
    });
  }

the print on the compiler shows the timer ticks as 1-2-3-4-5 but its taking it too long to print 2 and then same goes for the rest of the ticks. Anyone knows what is going on?

1

There are 1 best solutions below

0
On BEST ANSWER

Timer.periodic(const Duration(seconds: 5), (timer) { //do function } mean, it spent 5s to do this function

So, if you do this function 5 times, it will spent 25s

Change to 1s will work:

Timer.periodic(const Duration(seconds: 1), (timer) {
      print(timer.tick);
      counter--;
      if (counter == 2) {
        _StopDataCollection();
      }else if (counter == 1){
        createUser();
      }
      if (counter == 0) {
        print('Cancel timer');
        timer.cancel();
        print(numbers.length);
        print(fifo.length);
      }
    });

or use for-loop instead timer

for(int i = 0; i < 5; i++){
      await Future.delayed(Duration(seconds: 1));
      counter--;
      print(counter);
      if (counter == 2) {
        _StopDataCollection();
      }else if (counter == 1){
        createUser();
      }
      if (counter == 0) {
        print('Cancel timer');
        print(numbers.length);
        print(fifo.length);
      }
    }