Skip to content

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.

“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).”

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.

one-loop-tick.js
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.

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.

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.

await-ordering.js
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, c

A 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: 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.nextTick has 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.

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:

  1. Move work off the thread. Web Worker or worker_threads for CPU-bound work.
  2. Break work into chunks. Yield with setTimeout(fn, 0) or scheduler.yield() between batches.
  3. Use the right primitive. requestIdleCallback for background work, requestAnimationFrame for visual updates.
  1. Write down the synchronous statements in order; they all run first.
  2. Collect microtasks in the order they were queued.
  3. Print all microtasks, including the ones they queue.
  4. 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.

  1. What is the difference between process.nextTick and queueMicrotask?
  2. When does requestAnimationFrame run relative to microtasks?
  3. Why can await inside forEach not sequence work?
  4. How would you keep a 10,000-item render from blocking input?
  5. What happens to pending timers when a tab is backgrounded?
  • 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 setTimeout for animation. Use requestAnimationFrame; timers drift and are throttled.
  • Yielding with await Promise.resolve() to unblock the UI. It stays in the microtask queue.