Sub topic 3
Scheduling Microtasks Directly: queueMicrotask
This chapter assumes you know the model from the earlier chapters. The call stack runs synchronous code. Tasks wait in the task queue. The microtask queue is drained completely after each task.
Scheduling Microtasks Directly: queueMicrotask
queueMicrotask(fn) puts fn on the microtask queue without creating a promise. It runs in the same queue as promise reactions, in first-in, first-out (FIFO) order. MutationObserver callbacks in the browser also run as microtasks.
Predicting Output Order Step by Step
- Run all synchronous code.
- Drain every microtask, including any microtasks queued along the way.
- Take one task, run it, and repeat from step 2.
console.log('sync 1');
setTimeout(() => console.log('task'), 0);
queueMicrotask(() => console.log('microtask'));
Promise.resolve().then(() => console.log('promise'));
console.log('sync 2');
// Output: sync 1, sync 2, microtask, promise, taskRendering and requestAnimationFrame in the Browser Loop
The browser may render between tasks, but only after the microtask queue is empty. requestAnimationFrame callbacks run just before the next paint, usually about 60 times per second. Microtasks never let a paint happen in the middle of them.
The Node.js Event Loop and Its Phases
Node.js (through libuv) splits each loop iteration into phases. Each phase has its own queue.
| Phase | Runs |
|---|---|
| timers | `setTimeout` / `setInterval` callbacks |
| pending callbacks | some deferred system callbacks |
| poll | I/O callbacks; waits for I/O |
| check | `setImmediate` callbacks |
| close callbacks | `close` events |
process.nextTick and setImmediate
process.nextTick callbacks run before promise microtasks, as soon as the current operation finishes. setImmediate runs in the check phase. Inside an I/O callback, it always runs before a zero-delay timer.
// Run as a CommonJS script with Node.js
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
console.log('sync');
// Output: sync, nextTick, promiseBlocking the Loop and Starving It with Microtasks
A long synchronous loop blocks everything: timers, I/O, input, and rendering. A microtask that keeps queuing another microtask does the same thing in a less obvious way. The queue never empties, so no task or paint ever runs. Recursive process.nextTick starves Node.js in the same way.
Keeping Your App Responsive
You can split long work into chunks and schedule each chunk as a separate task:
function processInChunks(items, handle, chunkSize = 1000) {
let index = 0;
function nextChunk() {
const end = Math.min(index + chunkSize, items.length);
for (; index < end; index++) handle(items[index]);
if (index < items.length) setTimeout(nextChunk, 0);
}
nextChunk();
}
processInChunks(Array.from({ length: 100000 }, (_, i) => i), (n) => n * n);For CPU-heavy work, move it to a Web Worker in the browser or a worker_threads worker in Node.js. A worker has its own thread and its own event loop.
Exercise
What does this print? setTimeout(() => console.log('T'), 0); queueMicrotask(() => { console.log('M1'); queueMicrotask(() => console.log('M2')); }); console.log('S');
Show answer
S, M1, M2, T. The synchronous log runs first. M2 is queued while the microtask queue is being drained, so it still runs before the timer task.
Exercise
Why would replacing setTimeout(nextChunk, 0) with queueMicrotask(nextChunk) defeat the purpose of chunking?
Show answer
All the chunks would run in one microtask drain, so the browser would never get a chance to render or handle input between them.