Sub topic 10
Scheduling Microtasks Directly: queueMicrotask
Earlier chapters showed that promise reactions run as microtasks and that the microtask queue is fully drained after each task. Promises are not the only way to get code onto that queue. This chapter covers queueMicrotask, the direct API for scheduling a microtask, and MutationObserver, the DOM feature whose callbacks also run as microtasks.
This chapter assumes you already know how the call stack, task queue, and microtask queue interact, and that you can use .then() and closures comfortably.
The API in One Line
queueMicrotask(callback) adds callback to the end of the microtask queue. It takes no arguments beyond the function, returns undefined, and offers no way to cancel the callback. It is a global in all modern browsers, in Web Workers, in Deno, and in Node.js 11 and later.
It shares one FIFO queue with promise reactions. A microtask scheduled with queueMicrotask has no priority over a promise callback, and a promise callback has none over it. Whichever was queued first runs first.
console.log('sync start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise 1'));
queueMicrotask(() => console.log('microtask 1'));
Promise.resolve().then(() => console.log('promise 2'));
console.log('sync end');
// Output:
// sync start
// sync end
// promise 1
// microtask 1
// promise 2
// timeoutThe three microtasks interleave in exactly the order they were scheduled. The timer callback waits until the queue is empty, because it is a task.
Why Not Just Use Promise.resolve().then()?
Before queueMicrotask existed, the usual idiom was Promise.resolve().then(fn). That still works, but it differs in three ways.
| Aspect | `queueMicrotask(fn)` | `Promise.resolve().then(fn)` | `setTimeout(fn, 0)` |
|---|---|---|---|
| Queue | Microtask | Microtask | Task |
| Runs before rendering and next task | Yes | Yes | No |
| Objects allocated | None beyond the callback | Two promises | Timer handle |
| Thrown error becomes | Uncaught exception | Rejected promise (unhandled rejection) | Uncaught exception |
| Return value | `undefined` | A promise you can chain | Timer ID, cancellable |
| States intent clearly | Yes | Looks like promise logic | Yes, but different timing |
The error behaviour matters most in practice. When a queueMicrotask callback throws, the error is reported right away as an ordinary uncaught exception. In a browser it fires the error event on window. In Node.js it fires uncaughtException, which crashes the process if nothing handles it. When a .then() callback throws, the error turns into a rejected promise. It is reported only as an unhandled rejection, after the microtask queue has had a chance to attach a handler.
Run this as a Node.js script to see the difference:
process.on('uncaughtException', (err) => {
console.log('uncaughtException:', err.message);
});
process.on('unhandledRejection', (reason) => {
console.log('unhandledRejection:', reason.message);
});
queueMicrotask(() => {
throw new Error('from queueMicrotask');
});
Promise.resolve().then(() => {
throw new Error('from then');
});
// Output:
// uncaughtException: from queueMicrotask
// unhandledRejection: from thenThe allocation difference rarely matters in application code. It does matter in libraries that schedule microtasks on hot paths, such as state managers and reactive frameworks.
Use Case 1: Batching Work at the End of the Current Task
The most common use is coalescing many synchronous calls into one piece of work. Every call inside the same task adds to a buffer, and the first call schedules a single flush. That flush runs after the current synchronous code finishes but before the browser renders or any other task runs.
function createBatcher(flush) {
let pending = [];
let scheduled = false;
return function add(item) {
pending.push(item);
if (!scheduled) {
scheduled = true;
queueMicrotask(() => {
const batch = pending;
pending = [];
scheduled = false;
flush(batch);
});
}
};
}
const log = createBatcher((batch) => console.log('flush', batch));
log('a');
log('b');
log('c');
console.log('after adds');
// Output:
// after adds
// flush [ 'a', 'b', 'c' ]Frameworks use this pattern to group several state changes into one re-render. A microtask fits better than a timer here. The flush lands before the next paint, so the user never sees an intermediate state. A setTimeout flush could let the browser paint the stale UI first.
Note the order of the reset inside the callback. pending and scheduled are reset before flush runs. If flush calls add again, that call starts a fresh batch and schedules another microtask, so no item is lost.
Use Case 2: Making a Callback Consistently Asynchronous
A function that sometimes calls its callback synchronously and sometimes asynchronously is a classic bug source. Callers cannot know whether code after the call runs before or after the callback. A cache is the typical example: a cache hit can answer immediately, but a miss has to wait.
queueMicrotask makes the fast path asynchronous without adding a timer delay:
const cache = new Map();
function getData(key, callback) {
if (cache.has(key)) {
queueMicrotask(() => callback(cache.get(key)));
return;
}
setTimeout(() => {
const value = key.toUpperCase();
cache.set(key, value);
callback(value);
}, 10);
}
getData('x', (v) => {
console.log('first:', v);
getData('x', (v2) => console.log('cached:', v2));
console.log('after cached call');
});
// Output:
// first: X
// after cached call
// cached: XBoth paths now behave the same from the caller's side. The callback always runs after the code following the call.
MutationObserver: Microtasks from the DOM
MutationObserver watches a DOM node for changes such as attribute edits or added children. Its callback does not run once per change. The browser records each mutation and queues one microtask when the first mutation happens. Then it delivers every record collected up to that point in a single call.
Run this in a browser console:
const target = document.createElement('div');
const observer = new MutationObserver((records) => {
console.log('observer saw', records.length, 'mutations');
});
observer.observe(target, { attributes: true, childList: true });
target.setAttribute('data-a', '1');
target.appendChild(document.createElement('span'));
target.setAttribute('data-b', '2');
Promise.resolve().then(() => console.log('promise'));
console.log('sync done');
// Output:
// sync done
// observer saw 3 mutations
// promiseThe observer's microtask was queued at the first setAttribute, before the promise reaction existed, so it runs first. The two later mutations joined the pending batch and did not queue more microtasks. The element does not need to be attached to the document for this to work.
Gotchas
Microtasks queued during draining run in the same drain
The loop does not stop draining until the queue is empty, including microtasks added while it drains. A microtask that schedules another microtask keeps the loop from ever reaching rendering or the next task:
// Do not run this in a tab you care about: it freezes the page.
function forever() {
queueMicrotask(forever);
}
forever();A setTimeout loop written the same way would stay responsive, because each callback is a separate task. The chapter on blocking and starvation covers this failure mode in detail.
It does not yield to rendering
Developers sometimes reach for queueMicrotask to "let the browser update first." It cannot do that. A microtask runs before the next render step. To let a paint happen first, schedule a task or use requestAnimationFrame, which a later chapter covers.
Node.js has a queue that runs earlier
In Node.js, process.nextTick callbacks run before the promise and queueMicrotask queue. Code that mixes the two can surprise you. That ordering is covered in the chapter on process.nextTick and setImmediate.
Choosing a Scheduler
- Use
queueMicrotaskwhen work must happen after the current synchronous code but before anything else, such as rendering, input handling, or timers, and you are not working with promises. - Use
.then()orawaitwhen you already have a promise or want to chain results and handle errors as rejections. - Use
setTimeout, orsetImmediatein Node.js, when you want to yield to the event loop so input, I/O, and rendering can proceed.
Exercise
Predict the output of this code, then explain the position of "M2". queueMicrotask(() => { console.log('M1'); queueMicrotask(() => console.log('M2')); }); Promise.resolve().then(() => console.log('P1')); setTimeout(() => console.log('T1'), 0); console.log('S');
Show answer
The output is S, M1, P1, M2, T1. "S" is synchronous. M1 and P1 were queued in that order during the script, so they run first. M1 queues M2 while the queue is draining, which puts M2 behind P1 but still in the same drain. T1 is a task, so it runs only after the microtask queue is empty.
Exercise
In the createBatcher example, suppose you moved the line "scheduled = false;" to after "flush(batch);" and flush called add('d'). What would happen to 'd', and why?
Show answer
'd' would be pushed into the new pending array, but because scheduled is still true during flush, add would not schedule a microtask. After flush returns, scheduled becomes false, yet nothing is queued to flush 'd'. It sits in the buffer until some later add call schedules a flush. Resetting the state before calling flush avoids this lost update.
Exercise
A library replaces Promise.resolve().then(callback) with queueMicrotask(callback). A user's callback sometimes throws. In Node.js, with no error handlers installed, how does the observable behaviour change?
Show answer
Before the change, the throw became a rejected promise and was reported as an unhandled rejection. In current Node.js that also terminates the process by default, but only after the microtask queue drains, and it can be handled with an unhandledRejection listener. After the change, the throw is an uncaught exception reported immediately through uncaughtException, which crashes the process unless a listener for that event exists. Error-handling code that listens for unhandledRejection will no longer see these errors.