Sub topic 10
Scheduling Microtasks Directly: queueMicrotask
This chapter assumes you know how the microtask queue is drained after each task, and that promise reactions run as microtasks. Both were covered in earlier chapters. Here you will schedule a microtask yourself, without creating a promise.
The queueMicrotask API
queueMicrotask(callback) adds callback to the end of the microtask queue. It is available in browsers and in Node.js (version 11 and later). It returns undefined, and it does not take a delay or arguments.
Callbacks added this way share one queue with promise reactions, so they run in first-in, first-out order alongside them:
console.log('start');
setTimeout(() => console.log('timeout'), 0);
queueMicrotask(() => console.log('microtask 1'));
Promise.resolve().then(() => console.log('promise'));
queueMicrotask(() => console.log('microtask 2'));
console.log('end');
// Output: start, end, microtask 1, promise, microtask 2, timeoutAll three microtasks run after the synchronous code finishes and before the timer task, in the order they were queued.
Why not just use Promise.resolve().then()?
The two produce the same timing, but queueMicrotask has two advantages:
| Aspect | `Promise.resolve().then(fn)` | `queueMicrotask(fn)` |
|---|---|---|
| Allocations | Creates two promise objects | No promise created |
| Thrown error | Becomes an unhandled promise rejection | Reported as an ordinary uncaught exception |
| Intent | Reads as promise logic | States directly that you want a microtask |
The difference in errors matters. A rejection can be silently swallowed if someone later attaches a .catch. An exception thrown in a queueMicrotask callback goes straight to window.onerror or Node's uncaughtException.
A common use: batching work
Microtasks run after the current synchronous code and before the browser renders. That makes them a good place to collect several calls and handle them all at once:
const pending = [];
let scheduled = false;
function log(message) {
pending.push(message);
if (!scheduled) {
scheduled = true;
queueMicrotask(flush);
}
}
function flush() {
console.log('batch:', pending.join(', '));
pending.length = 0;
scheduled = false;
}
log('a');
log('b');
log('c');
console.log('sync done');
// Output: sync done, then batch: a, b, cFrameworks use this pattern to group several state changes into one update.
MutationObserver: microtasks from the DOM
In browsers, MutationObserver callbacks are also delivered as microtasks. Several DOM changes made in one synchronous run are reported together in a single callback:
const target = document.createElement('div');
new MutationObserver((records) => {
console.log('observer saw', records.length, 'changes');
}).observe(target, { attributes: true });
target.setAttribute('data-x', '1');
target.setAttribute('data-x', '2');
console.log('sync');
// Output: sync, then observer saw 2 changesBefore queueMicrotask existed, libraries toggled an attribute on a hidden node to get a microtask. Today you should call queueMicrotask directly.
Exercise
What does this print, and in what order? queueMicrotask(() => console.log('x')); setTimeout(() => console.log('y'), 0); Promise.resolve().then(() => { console.log('z'); queueMicrotask(() => console.log('w')); }); console.log('v');
Show answer
v, x, z, w, y. The synchronous log runs first. Then the microtask queue drains: x, then z, which queues w at the end of the same queue, so w runs before the queue empties. The timer task y runs last.
Exercise
An exception is thrown inside a callback passed to queueMicrotask. Is it reported as an unhandled promise rejection?
Show answer
No. It is reported as an ordinary uncaught exception, for example to window.onerror in a browser or the uncaughtException event in Node.js, because no promise is involved.