Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: Is using a zero duration timer the supported way of deferring work to the event loop

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?

like image 545
Jim Belton Avatar asked Nov 06 '12 03:11

Jim Belton


People also ask

How to delay the execution of a program using Dart timer?

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.

How to set a timer in async in Dart?

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.

What happens when a timer reaches 0?

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.

What is the granularity of the Dart timer?

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.


1 Answers

Current Answer

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/

Old Answer (pre Dart 1.0)

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.

like image 156
Justin Fagnani Avatar answered Sep 30 '22 14:09

Justin Fagnani