Sub topic 7
The Microtask Queue
This chapter assumes you already know the call stack, the task queue, and the basic event loop cycle from earlier chapters. You should also be comfortable with Promise.resolve().then(...) and setTimeout. Here we add the second queue the engine uses, the microtask queue. You will see when it runs, why it always beats timers, and the mistakes people make when they reason about it.
Why a Second Queue Exists
The task queue holds work such as timer callbacks, I/O completions, and user events. The event loop takes one task, runs it to completion, and then moves on. That works for coarse-grained events, but it is too slow for some kinds of follow-up work.
A promise reaction is a good example. If a .then() callback waited in the task queue, other tasks could run between a promise settling and its handler running. A timer could fire, a click handler could run, or the browser could repaint. Your code would then see the world in a state its author never expected.
The microtask queue fixes this. A microtask is a short callback that the engine runs as soon as the current JavaScript finishes and before anything else from outside gets a turn. Microtasks come from three main sources:
- Promise reactions (
.then,.catch,.finally, andawaitcontinuations) queueMicrotask(fn)MutationObservercallbacks in browsers
Later chapters cover promise reactions, async/await, and queueMicrotask in detail. This chapter is about the queue itself.
The Drain Rule
The behavior you need to remember fits in one sentence. Whenever the call stack becomes empty, the engine runs microtasks until the microtask queue is empty, including any microtasks added along the way.
The HTML specification calls this moment a microtask checkpoint. Node.js follows the same rule for promise microtasks. Two details matter:
- The queue is drained completely, not one item per turn. Compare this with the task queue, where the loop takes one task and then gives other steps a chance.
- Microtasks added during the drain run in the same drain. The engine keeps going until it finds the queue empty.
The loop on the right side is the key part. A task gets one pass. The microtask queue gets as many passes as it needs.
Microtasks Beat Timers
Here is the classic example again with the queues in mind:
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
// Output: A, D, C, BWalk through it:
- The script itself is a task. It logs
A. setTimeouthands a timer to the host. When it expires, the host puts the callback in the task queue.Promise.resolve()is already fulfilled, so.thenputs its callback in the microtask queue right away.- The script logs
Dand finishes. The stack is now empty. - Checkpoint: the microtask queue has the
Ccallback. It runs. - The microtask queue is empty. The loop takes the next task, the timer, and logs
B.
The delay of 0 does not matter. A timer callback is a task, and a task cannot start until the microtask queue drains.
Microtasks Queued by Microtasks
Because the drain continues until the queue is empty, a microtask that schedules another microtask still runs before the next task:
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => {
console.log('micro 1');
Promise.resolve().then(() => console.log('micro 2'));
});
console.log('sync');
// Output: sync, micro 1, micro 2, timeoutmicro 2 was added while the engine was draining, so it joins the same drain. The timer waits for both of them.
Draining Happens After Every Task
The checkpoint is not a one-time event at the end of your script. It happens after each task. Microtasks created inside a task run before the next task starts:
setTimeout(() => {
console.log('task 1');
Promise.resolve().then(() => console.log('micro after task 1'));
}, 0);
setTimeout(() => {
console.log('task 2');
}, 0);
// Output: task 1, micro after task 1, task 2Both timers are ready at about the same time, but they are still two separate tasks. Between them, the stack empties and the microtask queue drains.
The Checkpoint Depends on the Stack, Not the Task
The precise trigger is "the call stack is empty," not "a task ended." This difference shows up with event listeners. When a user clicks a button, the browser calls each listener directly from the event loop. The stack empties after each listener, so microtasks run between them. When your own code calls button.click(), your script is still on the stack while the listeners run, so the checkpoint waits.
// Run in a browser console
const button = document.createElement('button');
button.textContent = 'Click me';
document.body.append(button);
button.addEventListener('click', () => {
Promise.resolve().then(() => console.log('micro 1'));
console.log('listener 1');
});
button.addEventListener('click', () => {
Promise.resolve().then(() => console.log('micro 2'));
console.log('listener 2');
});
button.click();
// Programmatic click: listener 1, listener 2, micro 1, micro 2
// Now click the button with the mouse:
// Real click: listener 1, micro 1, listener 2, micro 2The same listeners produce different orders. Tests that fire events with .click() or dispatchEvent can therefore pass while real users see different behavior. This matters most when one listener's microtask changes state that a later listener reads.
Tasks and Microtasks Compared
| Property | Task (macrotask) | Microtask |
|---|---|---|
| Typical sources | `setTimeout`, `setInterval`, I/O, user events, `MessageChannel` | Promise reactions, `await`, `queueMicrotask`, `MutationObserver` |
| How many run per loop turn | One | All of them, until the queue is empty |
| When it runs | When the loop picks it, after the previous checkpoint | Whenever the call stack becomes empty |
| Rendering between items | Possible | Never |
| Added during processing | Waits for a later turn | Runs in the same drain |
Common Mistakes
Treating setTimeout(fn, 0) and .then(fn) as equivalent "run later" tools. Both defer work, but at very different points. A microtask runs before any rendering or input handling. A task may run after a repaint and after other events. If you want to give the browser a chance to paint, a microtask will not help.
Assuming a long chain of .then calls lets other work in. Every step of a chain runs in the same drain, as long as each step settles synchronously. A thousand chained .then callbacks act like one long block of synchronous code from the user's point of view.
Thinking microtasks run "in parallel." They run on the same single thread as everything else, one at a time, each to completion. The microtask queue changes the order of work, not whether that work can happen at the same time as other work.
Assuming the microtask queue drains only at the end of the script. It drains every time the stack empties: after the main script, after each timer callback, after each user-triggered listener, and after each I/O callback.
Summary
The microtask queue holds small follow-up jobs, mainly promise reactions. Whenever the call stack empties, the engine drains the whole queue, including microtasks added during the drain, before it picks another task or renders. This is why promise callbacks always run before zero-delay timers, why microtasks scheduled inside a task run before the next task, and why microtasks that keep scheduling more microtasks can lock up the loop.
Exercise
Predict the output of this code and explain each step: setTimeout(() => console.log('T1'), 0); Promise.resolve().then(() => { console.log('M1'); setTimeout(() => console.log('T2'), 0); Promise.resolve().then(() => console.log('M2')); }); console.log('S');
Show answer
The output is S, M1, M2, T1, T2. The script logs S, having queued timer T1 as a task and M1 as a microtask. When the stack empties, the drain runs M1. M1 queues timer T2 as a task behind T1 and queues M2 as a microtask. M2 joins the same drain, so it runs next. The microtask queue is now empty, so the loop runs task T1 and then task T2 in the order they were queued.
Exercise
Two click listeners on the same button each queue a promise callback and then log a message. A unit test calls button.click() and records the order listener 1, listener 2, micro 1, micro 2. A user clicking the real button sees listener 1, micro 1, listener 2, micro 2. Why do the orders differ?
Show answer
The microtask checkpoint happens when the call stack becomes empty. For a real click, the browser calls each listener from the event loop, so the stack empties after listener 1 and its microtask runs before listener 2. With button.click(), the test code that called click() stays on the stack while both listeners run, so the stack does not empty until click() returns. Both microtasks then run after both listeners.
Exercise
A developer replaces setTimeout(updateProgressBar, 0) with queueMicrotask(updateProgressBar) inside a long loop of work that is split into steps, hoping the progress bar will repaint more often. What happens, and why?
Show answer
The progress bar repaints less often, possibly only once at the end. Rendering happens only after the microtask queue is empty and the loop moves between tasks. Microtasks run before rendering, and any microtasks they schedule join the same drain. So moving the steps from tasks to microtasks removes the points where the browser could paint.