JavaScriptHard
How does the event loop work internally?
Internally, the browser's event loop repeatedly picks one task from its task queues, runs it to completion, performs a microtask checkpoint (draining every microtask), and then, when a frame is due, runs the rendering steps; Node.js runs a different, phase-based loop built on libuv.
The browser loop, per the HTML spec
- Pick a task. There are several task queues (user input, timers, networking, messaging). The browser may prioritise some, for example input over timers, but runs tasks from the same queue in order.
- Run it on the call stack until the stack is empty.
- Microtask checkpoint: run microtasks until the queue is empty, including ones added during this step (promise reactions,
queueMicrotask,MutationObserver). - Update the rendering if a frame is due (roughly every 16.7 ms at 60 Hz, only for visible documents): run
requestAnimationFramecallbacks, then style, layout and paint.IntersectionObserverandResizeObservercallbacks also run around this step. - If there is spare time, run
requestIdleCallbackcallbacks.
Important consequences
- A
Promise.thenchain that keeps adding microtasks starves rendering and input. requestAnimationFrameis the right place for visual updates: it runs just before paint.setTimeout(fn, 0)is clamped to at least 4 ms after 5 nested levels, and heavily throttled in background tabs.- Long tasks (over 50 ms) hurt INP (Interaction to Next Paint). Break work into chunks or move it to a Web Worker;
scheduler.postTaskandscheduler.yield()give finer control where supported.
Node.js (libuv) phases
timers (setTimeout/setInterval) → pending callbacks → poll (I/O) → check (setImmediate) → close callbacks. Between each callback, Node drains process.nextTick callbacks first, then promise microtasks.
Code example
js
1const log = (msg) => console.log(`${performance.now().toFixed(1).padStart(6)}ms ${msg}`);23log("task 1: script starts");45setTimeout(() => log("task 2: timer (next task)"), 0);67// globalThis.x?.() is safe even where the API does not exist (workers, Node)8globalThis.requestAnimationFrame?.(() => log("rendering step: requestAnimationFrame (before paint)"));910Promise.resolve().then(() => {11 log("microtask A");12 queueMicrotask(() => log("microtask C (added while draining, still runs before the timer)"));13});14queueMicrotask(() => log("microtask B"));1516// A long task blocks everything else17const start = performance.now();18while (performance.now() - start < 30); // 30ms of busy work19log("task 1: script ends (after a 30ms long task)");2021// Order you will see:22// task 1 starts -> task 1 ends -> microtask A -> microtask B -> microtask C23// -> timer task (and the rAF callback around the next frame, in a browser)24await new Promise((r) => setTimeout(r, 60));
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.