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

6,164

Solution 1

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!!

Solution 2

Use Timer if:

  • You want the ability to cancel it. With Timer.cancel() you cancel the timer unlike Future where you'll have to make use of CancelableCompleter to cancel the Future.

  • If you don't want to return anything in your callback method.

    Example:

    // Prints 'Hello' after 1s. 
    var timer = Timer(Duration(seconds: 1), () => print('Hello'));
    

    And in case you decide to cancel it, use:

    timer.cancel();
    

Use Future if:

  • Your code can throw errors and you want to catch them. Had you used Timer and any uncaught exceptions occurs, the app will exit.

  • You want to return something from your callback method.

    Example:

    // Return 'Hello' after 1s and if there is any error, it will be caught. 
    Future
      .delayed(Duration(seconds: 1), () => 'Hello')
      .catchError((err) {}); 
    

Solution 3

Timer:

Timer() creates a Timer object, that runs your computation after a delay. Since you get the reference to that Timer object, you can choose to cancel it before it's fired, by calling cancel.

Timer t = Timer(Duration(seconds: 1), () => print("1 sec later"));
t.cancel(); // nothing will be printed out

Future:

Future.delayed creates a Future that runs its computation after a delay. Internally, it's still using a Timer to do that. It does not expose the timer to you, so you cannot control or cancel it. On the bright side, you get to do your normal Future stuff, like await on it.

await Future.delayed(Duration(seconds: 1);
print("1 sec later");

Solution 4

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.

Share:
6,164
bingcheng45
Author by

bingcheng45

A good problem solver is a good googler. Hey I have some Kinect projects and guides!

Updated on November 21, 2022

Comments

  • bingcheng45
    bingcheng45 over 1 year

    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*/ });