Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Future.delayed vs Timer in flutter

I like to know the differences between Future.delayed and Timer method for delaying code execution. Both seem to do the same thing.

Future.delayed

Future.delayed(const Duration(milliseconds: 500), () { /*code*/ });

VS

Timer

Timer _timer = new Timer(const Duration(milliseconds: 500), () { /*code*/ });
like image 995
bingcheng45 Avatar asked Apr 04 '20 18:04

bingcheng45


2 Answers

The timer runs its job after the given duration, but flutter not waiting for it to complete its execution, it performs below statements.

Example:

Timer(Duration(seconds: 2), () {
      print("Execute this code afer 2 seconds");
    }); 
 print("Other code");

Output:

Other code
Execute this code after 2 seconds

So as you can see code below timer will execute first and then the timer will be performed. Also, Timer can be stopped at any given point before its execution, if we crate the object of it.

 Timer timer = Timer(Duration(seconds: 2), () {
          print("Execute this code afer 2 seconds");
        }); 
timer.cancel();

The future also runs its job after the given duration, but its return future object means we can use await to get its execution first, and then below statements will be going to execute.

 await Future.delayed(Duration(seconds: 2), () {
          print("Execute this code afer 2 seconds");
        });
        print("My Code");
    print("Other code");

Output:

Execute this code after 2 seconds
Other code

The main disadvantage of the future is that we can't cancel it in between.

like image 116
Jitesh Mohite Avatar answered Sep 18 '22 18:09

Jitesh Mohite


A couple of differences for me.

  • Future.of returns a Future.
  • Timer does not return anything.

So if your delayed code returns anything that you need to continue your working, Future is the way to go.


Other difference is that the Timer class provides a way to fire repeatedly.

This quote is from the Timer Class Reference documentation itself

A count-down timer that can be configured to fire once or repeatedly

And example to use Timer with the repeat could be

Timer.periodic(Duration(seconds: 5), (timer) {
    print(DateTime.now()); 
});

Other frecuent example is to create a stopwatch, to measure timings in your code, it's usually seen using a Timer.

GL!!

like image 33
encubos Avatar answered Sep 17 '22 18:09

encubos