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*/ });
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.
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!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With