In Dart, how does the event queue/event loop differ between Dart2JS and the Dart VM?


Is there any difference in the order of execution?

Or does the event queue/loop work differently in JavaScript than Dart?


DOM events are handled by the Blink. These events should therefore be handled the same way. In JavaScript there is no other event loop (afaik). For example, a common pattern for yielding execution is window.setTimeout(0, continuation).

In Dart we also have asynchronous events that are handled by dart:async. There we can distinguish between instants and cycles. An instant is composed of one or more cycles. An instant executes all its cycles until there is none left and then moves to the next instant. DOM events are at the same level as instants. That is, a DOM event will never be interleaved with cycles of the same instant. [^1] (This also means that piling up cycles within the same instant can starve the DOM.)

runAsync queues a new cycle. queues a new instant.

Futures and Streams use cycles to queue events that can be executed immediately. In the following example both thens will be scheduled within the same instant and therefore run before any DOM event has the chance to interfere.

var future = new Future.value(499);

There are other small differences between Dart and JavaScript: Dart does not have a minimal sleep time for Timer runs. In JavaScript window.setTimeout is not allowed to execute the computation before 5ms. (This is due to unfortunate historic circumstances). Dart doesn’t have this restriction. [^2]

The VM’s Timer functionality is not based on DOM, and has its own implementation. As of May 2013 the ordering of scheduled timer callbacks is not consistent between JavaScript (and thus dart2js) and the VM. (I’m not sure about Dartium, but I believe it uses the DOM’s version and is thus similar to JavaScript).

We are currently discussing changes to the library to guarantee that Timer events are executed in the “correct” order and not just after the waiting-time has elapsed.

[^1] This is not correctly implemented. As of May 2013 ever asynchronous operation is built on top of Timer.

[^2] This, too, is not done yet (May 2013). I’m not sure about Dartium, but dart2js currently still uses window.setTimeout. It will eventually switch to newer primitives (on browsers that support it) that allow for more precise timeouts.

Answered By – Florian Loitsch

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *