Predicting Output Order with the Browser Event Loop
Stacks & QueuesModel answerLast updated
Work out the print order of a short script mixing timers, promises and microtasks, then explain how the browser event loop schedules each kind of task.
Scheduling in a Single-Threaded Runtime
JavaScript runs your code on one thread, yet pages stay responsive while timers, network calls and promises are in flight. The event loop makes that possible.
Consider this script, executed as a normal top-level script in a modern browser:
console.log('first');
setTimeout(() => console.log('timer'), 0);
Promise.resolve().then(() => console.log('promise'));
queueMicrotask(() => console.log('micro'));
console.log('last');
What to cover
- State the exact order in which the five messages are printed, and justify it step by step.
- Explain the difference between a macrotask (for example a
setTimeoutcallback) and a microtask (for example a.thencallback or aqueueMicrotaskcallback). - Describe what the event loop does once the call stack becomes empty, and in what order it picks the next piece of work.
- Say what happens when a microtask schedules another microtask, and what happens if that never stops.
Assumptions
- A standard modern browser, not Node.js.
- Think in terms of the call stack, the task queue and the microtask queue.
- Mention, briefly, how
async/awaitfits into the same model.
Hints
Hint 1
Start by separating what runs immediately on the call stack from what is merely queued for later. Only two of the five lines are purely synchronous.
Hint 2
There are two different queues. Ask which one is emptied completely before the loop moves on, and where the top-level script itself fits in (it is a task too).
Hint 3
A microtask that enqueues another microtask is appended to the same queue and runs in the same drain. Think about what that implies for a microtask that keeps re-enqueueing itself.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Output order
first
last
promise
micro
timer
Why
The browser runtime has three pieces that matter here:
- Call stack: runs synchronous code one frame at a time. Nothing else can run while it is non-empty.
- Task (macrotask) queue: holds timer callbacks, DOM and user events, network callbacks,
MessageChannelmessages, and the initial script itself. - Microtask queue: holds promise reactions (
.then,.catch,.finally),queueMicrotaskcallbacks,MutationObservercallbacks, and the continuations afterawait.
The loop, in simplified form:
repeat:
take ONE task from the task queue and run it to completion
drain the microtask queue completely (including newly added microtasks)
if a render is due: run rAF callbacks, style, layout, paint
Trace
| Step | Action | Printed | Microtask queue | Task queue |
|---|---|---|---|---|
| 1 | console.log('first') | first | empty | empty |
| 2 | setTimeout(..., 0) | empty | [timer] | |
| 3 | Promise.resolve().then(...) | [promise] | [timer] | |
| 4 | queueMicrotask(...) | [promise, micro] | [timer] | |
| 5 | console.log('last') | last | [promise, micro] | [timer] |
| 6 | Script finishes, stack empty, microtask checkpoint | promise, micro | empty | [timer] |
| 7 | Next task | timer | empty | empty |
The script itself is the first task. When it finishes and the stack is empty, the engine performs a microtask checkpoint before anything else is allowed to run, so both microtasks print before the timer. .then and queueMicrotask share one queue, so they run in FIFO order of enqueueing, giving promise before micro.
Macrotask vs. microtask
- Macrotask: a unit of work scheduled by the host (timer, input event, I/O). The loop runs one per iteration, and the browser may render between tasks.
setTimeout(fn, 0)means "run no sooner than roughly 0 ms, and only after the current task and its microtasks are done", not "immediately". Nested timers are also clamped to about 4 ms after a few levels, and background tabs are throttled harder. - Microtask: a short follow-up job that runs as soon as the stack empties, before rendering and before the next task. They are meant for work that must happen "right after this code, but not synchronously", such as promise resolution handling.
When the stack empties
- Run all microtasks until the queue is empty. Microtasks added during this phase are appended and run in the same checkpoint.
- Optionally render if a frame is due.
- Pick the next task and repeat.
So a microtask that schedules another microtask still runs before any timer:
Promise.resolve().then(() => {
console.log('p1');
queueMicrotask(() => console.log('p2'));
});
setTimeout(() => console.log('t'), 0);
// p1, p2, t
Starvation
function spin() { Promise.resolve().then(spin); }
spin();
The microtask queue never becomes empty, so the loop never reaches rendering, input handling or timers. The page freezes much like while (true) {}. A recursive setTimeout is different: each iteration is a separate task, so the browser can paint and handle input between them. Rule of thumb: break long or repeating work into tasks (setTimeout, MessageChannel, scheduler.postTask), not microtasks.
async/await
async/await is syntax over promises, so the same rules apply:
async function f() { console.log('1'); await null; console.log('3'); }
f(); console.log('2');
// 1 2 3
Code before the first await runs synchronously. Everything after an await is a microtask continuation. Awaiting a native promise costs one tick in modern engines. Resolving a promise with another promise or thenable can add extra ticks, which occasionally changes interleavings in subtle ways.
Cost
Each callback is enqueued and dequeued once, so n callbacks cost O(n) time and space. The practical concern is latency: a long microtask chain delays every task and every frame.
Reference simulation
from collections import deque
class Loop:
def __init__(self):
self.tasks, self.micro, self.out = deque(), deque(), []
def drain(self):
while self.micro: # includes microtasks added while draining
self.micro.popleft()()
def run(self, script):
script() # the script is the first task
self.drain()
while self.tasks:
self.tasks.popleft()()
self.drain() # a render opportunity would come here
return self.out
Common mistakes
- Saying
setTimeout(0)runs "right after" the current code, ignoring the microtask checkpoint. - Treating promise callbacks as macrotasks.
- Believing the microtask queue is processed one item per loop turn, when it is drained fully.
- Forgetting that the top-level script is itself a task.
- Applying Node.js rules to a browser question. In Node,
process.nextTickruns before promise microtasks, and the timers, poll and check phases makesetTimeout(0)vs.setImmediateordering differ.
What a strong answer shows
A mechanistic explanation (stack, then microtask checkpoint, then render, then next task) rather than a memorized ordering, plus awareness of starvation, rendering, and the browser vs. Node distinction.