I discovered by experimenting that creating a timer with a duration of 0 allows me to defer work into the event queue. I really like this feature, because it allows avoiding a lot of nasty reentrancy issues. Is this intentional functionality that will not change? Can it be added to the documentation? If not, is there a supported way to do this?
Timer class will allow specifying the time which you need to delay the execution and after that time period code will be executed inside the Timer. import 'dart:async'; Timer (Duration (seconds:2), () { setState ( () { greeting = "After Some time"; }); }); For the duration you can set any value based on your need.
import 'dart:async'; Timer (Duration (seconds:2), () { setState ( () { greeting = "After Some time"; }); }); For the duration you can set any value based on your need. It accept seconds, minute, hours etc.
The timer counts down from the specified duration to 0. When the timer reaches 0, the timer invokes the specified callback function. Use a periodic timer to repeatedly count down the same interval.
Note: If Dart code using Timer is compiled to JavaScript, the finest granularity available in the browser is 4 milliseconds. See Stopwatch for measuring elapsed time.
The proper way to do this is with scheduleMicrotask(Function callback)
.
See the API documentation here: https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-async#id_scheduleMicrotask
A great article on async tasks and the event loop is here: https://www.dartlang.org/articles/event-loop/
For now, the answer is yes, new Timer(0, callback)
is the easiest way to defer a function call.
Soon, hopefully, http://dartbug.com/5691 will be fixed and there will be a better way. The problem with Timer is that the HTML spec says that the callback should happen no sooner than 4ms later. Depending on what you're doing that can be on issue.
Microsoft introduced setImmediate()
to solve this. It invokes the callback at the beginning of the next event loop, after any redraws. My preferred solution in Dart is to have Future.immediate()
defer until the next event loop, and possibly a function like defer()
that takes a callback.
But new Timer(0, f)
will still work, even after a better solution is available. I wouldn't mind a lint warning for it though.
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