scheduleMicrotask function
- voidcallback()
Runs a function asynchronously.
Callbacks registered through this function are always executed in order andare guaranteed to run before other asynchronous events (likeTimer events,or DOM events).
Warning: it is possible to starve the DOM by registering asynchronouscallbacks through this method. For example the following program runsthe callbacks without ever giving the Timer callback a chance to execute:
main() { Timer.run(() { print("executed"); }); // Will never be executed. foo() { scheduleMicrotask(foo); // Schedules [foo] in front of other events. } foo();}Other resources
- The Event Loop and Dart:Learn how Dart handles the event queue and microtask queue, so you can writebetter asynchronous code with fewer surprises.
Implementation
@pragma('vm:entry-point', 'call')void scheduleMicrotask(void Function() callback) { _Zone currentZone = Zone._current; if (identical(_rootZone, currentZone)) { // No need to bind the callback. We know that the root's scheduleMicrotask // will be invoked in the root zone. _rootScheduleMicrotask(null, null, _rootZone, callback); return; } _ZoneFunction implementation = currentZone._scheduleMicrotask; if (identical(_rootZone, implementation.zone) && _rootZone.inSameErrorZone(currentZone)) { _rootScheduleMicrotask( null, null, currentZone, currentZone.registerCallback(callback), ); return; } Zone.current.scheduleMicrotask(Zone.current.bindCallbackGuarded(callback));}