Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter timer.periodic is slower than real life

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
      }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading