The Event Loop
The event loop is the mechanism that lets a single-threaded language handle I/O, timers and user
input without blocking on any of them. When you can predict the order of console output in a snippet
that mixes setTimeout, Promise.then and synchronous code, you understand it.
The 60-second answer
Section titled “The 60-second answer”“JavaScript has one call stack. Synchronous code runs until the stack is empty. Work that cannot be
done on the stack — timers, network, DOM events — is handed to the host, which calls back with a
task. Each iteration of the event loop takes one task from the task queue, runs it to completion,
then drains the entire microtask queue before touching the next task or rendering. Promise
callbacks and queueMicrotask are microtasks; setTimeout, I/O and UI events are tasks. That is
why setTimeout(fn, 0) always runs after Promise.resolve().then(fn).”
The pieces
Section titled “The pieces”| Piece | Holds | Examples |
|---|---|---|
| Call stack | Frames of running functions | Any normal function call |
| Microtask queue | Short follow-ups, drained after every task | .then, .catch, .finally, await continuation, queueMicrotask |
| Task queue (macrotasks) | One-off callbacks | setTimeout, setInterval, I/O completion, UI events |
| Render steps | Style, layout, paint | Run between tasks, in the browser |
Run-to-completion means no function is ever pre-empted. The cost is that one slow function blocks everything: no timers, no rendering, no input handling.
console.log('1: sync');setTimeout(() => console.log('5: task'), 0);Promise.resolve() .then(() => console.log('3: microtask')) .then(() => console.log('4: second microtask'));queueMicrotask(() => console.log('3.5: microtask too'));console.log('2: sync again');Output: 1, 2, 3, 3.5, 4, 5. The stack empties, the microtask queue drains completely — including
microtasks queued by microtasks — and only then does the loop pick the timer task.
Timers are not exact
Section titled “Timers are not exact”setTimeout(fn, 0) means “at least 0 ms from now”. Browsers clamp nested timers to about 4 ms after
five levels, and background tabs are throttled much harder. Timers are ordered by expiry, and a
timer due at 0 ms still waits for the current task and all microtasks.
setTimeout(fn, 0) |
queueMicrotask(fn) |
|
|---|---|---|
| Queue | Task | Microtask |
| Runs before next render | No | Yes |
| Ordering versus promises | After | FIFO with .then |
| Typical use | Yield to the renderer | Defer consistency work, batch notifications |
requestAnimationFrame is a third thing: it runs just before paint, once per frame, and it is the
correct place for animation. Do not animate with setTimeout.
Promises and await are microtasks
Section titled “Promises and await are microtasks”await desugars to a .then continuation. Everything after an await runs in a microtask, which
is why an async function appears to pause: it returns control to the caller and resumes later.
async function main() { console.log('a'); await null; // continuation scheduled as a microtask console.log('c'); // runs after the sync code below}console.log('start');main();console.log('b');// start, a, b, cA common trap: await inside a loop yields the stack, not the tab. Other tasks still interleave
between iterations; it does not make the loop parallel either.
Browser versus Node
Section titled “Browser versus Node”- Browser: task queue plus a rendering pipeline. The loop picks a task, drains microtasks, then may run animation callbacks, then style/layout/paint. Input events are tasks.
- Node: libuv phases — timers, pending callbacks, poll (I/O), check (
setImmediate), close.process.nextTickhas its own queue that runs before promise microtasks.
setImmediate versus setTimeout(0) is only deterministic inside an I/O callback, where
setImmediate wins. Do not rely on it at top level.
Starvation and long tasks
Section titled “Starvation and long tasks”A task that takes 300 ms delays every timer and every frame by 300 ms. Microtask starvation is worse: the queue is drained before rendering, so an infinite microtask chain freezes the page with no chance to paint.
Fixes, in order of preference:
- Move work off the thread. Web Worker or
worker_threadsfor CPU-bound work. - Break work into chunks. Yield with
setTimeout(fn, 0)orscheduler.yield()between batches. - Use the right primitive.
requestIdleCallbackfor background work,requestAnimationFramefor visual updates.
How to answer an ordering question
Section titled “How to answer an ordering question”- Write down the synchronous statements in order; they all run first.
- Collect microtasks in the order they were queued.
- Print all microtasks, including the ones they queue.
- Then take the earliest timer or I/O task and repeat from step 1.
Say this out loud in the interview. Interviewers grade the method as much as the answer.
Follow-up questions
Section titled “Follow-up questions”- What is the difference between
process.nextTickandqueueMicrotask? - When does
requestAnimationFramerun relative to microtasks? - Why can
awaitinsideforEachnot sequence work? - How would you keep a 10,000-item render from blocking input?
- What happens to pending timers when a tab is backgrounded?
Common traps
Section titled “Common traps”- Assuming
setTimeout(0)runs before a resolved promise. Promises are microtasks; they win. - Assuming microtasks run on another thread. They run on the same stack, immediately.
- Using
setTimeoutfor animation. UserequestAnimationFrame; timers drift and are throttled. - Yielding with
await Promise.resolve()to unblock the UI. It stays in the microtask queue.