Skip to content

11. The JavaScript Runtime and the Event Loop

“JavaScript is single-threaded, which is why everything on the web happens one thing at a time, very quickly, until it doesn’t.”

A small restaurant has one cook. Orders come in on slips; the cook takes one slip, makes the dish completely, then takes the next. If a slip says “slow-cook a biryani for 40 minutes,” the cook doesn’t stand stirring it; they put it on the stove, set a timer, and take the next slip. When the timer rings, a new slip (“the biryani is ready, plate it”) goes on the pile.

There’s also a small pad of urgent notes by the stove. Whenever the cook finishes a dish, before touching the next slip, they read every urgent note — including any new urgent notes written while reading the old ones. Only when the pad is empty do they look up.

And every so often, a waiter shouts “PASS!” — the plates on the pass must be refreshed for the dining room. The cook does that between slips, if a refresh is due.

That cook is the main thread. The order slips are tasks. The urgent pad is the microtask queue. “PASS!” is the browser’s rendering opportunity. And the biryani timer is every asynchronous API you’ve ever used. If you understand this kitchen, you understand Promise ordering puzzles, why an infinite then chain freezes a page, and why breaking up long work makes taps feel instant.

But first: how does the cook read the recipes at all?

Your JavaScript arrives as text. Before it runs, the engine (V8 in Chromium; JavaScriptCore in Safari; SpiderMonkey in Firefox — similar ideas, different names) has to turn it into something the CPU can execute.

1. Parsing. The source is tokenized and parsed into an AST. Parsing is not free; on a mid-range phone, parsing a megabyte of JavaScript takes on the order of a few hundred milliseconds or more. V8 uses lazy parsing: for functions that aren’t called immediately, it does a fast “pre-parse” (just enough to find the function’s boundaries and syntax errors) and fully parses them only when first called. Functions wrapped in parentheses or called immediately are parsed eagerly.

2. Bytecode (Ignition). The AST is compiled to compact bytecode, which V8’s interpreter, Ignition, executes. Starting with an interpreter means code can begin running quickly, without waiting for expensive optimization.

3. JIT tiers. As code runs, V8 collects feedback: what types flow through each operation. Hot code is promoted through faster tiers:

  • Sparkplug — a very fast baseline compiler that turns bytecode into machine code without optimization. Cheap, quick win.
  • Maglev — a mid-tier optimizing compiler: fast to compile, decent code.
  • TurboFan — the top-tier optimizing compiler: uses type feedback to generate highly specialized machine code (“this + always sees two small integers”).

4. Deoptimization. Optimized code makes assumptions. If they break (“this function always got numbers, now it got a string”), V8 deoptimizes: throws away the optimized code and falls back to the interpreter, later perhaps re-optimizing. Frequent deopts are a performance smell in hot code.

V8 compilation pipelineSource text is parsed (lazily or eagerly) into an AST, compiled to bytecode run by the Ignition interpreter. Hot functions are compiled by Sparkplug (baseline), then Maglev (mid-tier), then TurboFan (top tier) using type feedback. A red deoptimize arrow returns from optimized code to the interpreter when assumptions break.SourceParselazy/eagerIgnitionbytecodeSparkplugbaselineMaglevmid-tierTurboFantop tierhotter code, more feedback →deoptimize when type assumptions break
Figure 11.1. V8's pipeline. Code starts fast in the interpreter and climbs through compiler tiers as it gets hot; broken type assumptions send it back down.

Hidden classes and inline caches, at whiteboard level

Section titled “Hidden classes and inline caches, at whiteboard level”

JavaScript objects are dynamic: you can add properties anytime. That would make every property access a slow dictionary lookup. V8 fakes structure: objects created the same way share a hidden class (V8 calls them “maps” or “shapes”) describing their layout — x at offset 0, y at offset 1. A property access site remembers the shape it saw last and the offset (an inline cache). If the next object has the same shape, access is a single memory load.

Practical upshot: create objects with the same properties in the same order; don’t add and delete properties on hot objects; keep functions monomorphic (seeing one shape) in hot paths. You rarely need to think about this in UI code — but it explains why some “harmless” code patterns are mysteriously slow in tight loops.

Why a byte of JavaScript costs more than a byte of image

Section titled “Why a byte of JavaScript costs more than a byte of image”

A 170 KB JPEG and a 170 KB (compressed) JavaScript bundle take about the same time to download. After that, their costs diverge wildly:

  • The image is decoded (often off the main thread, often hardware-accelerated) and drawn. Done.
  • The JavaScript (perhaps 600 KB once decompressed) must be parsed, compiled, and executed on the main thread — and executing it typically creates objects, DOM nodes and event listeners, which cost memory and trigger style/layout. On Priya’s phone, that’s hundreds of milliseconds of main-thread time during which taps wait.

That’s why the performance community budgets JavaScript separately and far more strictly than images. JavaScript is the most expensive byte you can send.

JS bytes vs image bytesTwo rows. Image 170 kilobytes: download, then a short decode on a background thread, then paint. JavaScript 170 kilobytes compressed: same download, then long main-thread parse, compile and execute blocks.170 KB imagedownloaddecode**off main thread170 KB JSdownloadparse+compileexecute (main thread)
Figure 11.2. Same bytes over the wire, very different costs. Images decode mostly off-thread; JavaScript must be parsed, compiled and executed on the main thread.

Memory: stack, heap and garbage collection

Section titled “Memory: stack, heap and garbage collection”

The stack holds function call frames: local primitive values and references, pushed on call and popped on return. Fast, small, automatically managed.

The heap holds everything else: objects, arrays, closures, strings. JavaScript has no free(); the engine’s garbage collector reclaims objects that are no longer reachable from the roots (globals, the current stack, the DOM).

V8’s GC (named Orinoco) is generational, based on the observation that most objects die young:

  • New objects go in the young generation (a small space). A fast scavenge (minor GC) copies surviving objects out and discards the rest. Frequent, short.
  • Objects that survive a couple of scavenges are promoted to the old generation. It’s collected by mark-sweep-compact (major GC): mark everything reachable, sweep the rest, compact to reduce fragmentation. Much of this is done concurrently on helper threads and incrementally in small slices, but there are still short main-thread pauses.

In a trace, GC appears as “Minor GC” and “Major GC” blocks. Lots of minor GCs during an interaction means lots of short-lived allocation (e.g., creating big arrays of objects on every keystroke). A major GC mid-animation is a dropped frame.

A leak is memory that’s still reachable but no longer useful. Common culprits:

  • Detached DOM nodes: elements removed from the document but still referenced from JS (a cached array of rows, a closure in a listener). The whole subtree stays alive.
  • Forgotten listeners and timers: window.addEventListener('resize', handler) in a component that never removes it; setInterval never cleared. The handler’s closure keeps everything it references alive.
  • Closures capturing big things: a callback that only needs an ID but closes over the entire data set.
  • Unbounded caches and global maps.

In SPAs, leaks accumulate across route changes: memory grows every navigation until the tab gets slow or, on iOS, killed.

Finding them: DevTools Memory panel → take a heap snapshot, perform an action several times (navigate away and back), take another, and compare. Filter by “Detached” to find detached DOM trees. The retainers view shows the chain of references keeping an object alive — usually ending at your forgotten listener.

Now the kitchen, precisely. The browser’s main thread runs an event loop:

  1. Pick one task from a task queue and run it to completion. A task is: running a <script>, dispatching a user event (click, keydown), a setTimeout/setInterval callback, a postMessage handler, a network callback, etc. (There are several task queues with different priorities; the browser chooses which to serve. Input events are typically prioritized.)
  2. Drain the microtask queue. Run every microtask, including microtasks queued by microtasks, until the queue is empty. Microtasks are: Promise reactions (.then/.catch/.finally callbacks), await continuations, queueMicrotask(), MutationObserver callbacks.
  3. Maybe render. If it’s time for a new frame (roughly every VSync, and only if something changed and the page is visible), run the rendering steps: process scroll and resize events, run requestAnimationFrame callbacks, run style, layout, IntersectionObserver/ResizeObserver steps, paint, then commit to the compositor (Chapter 10).
  4. If idle (nothing urgent, time left before the next frame), run requestIdleCallback callbacks.
  5. Repeat.
The event loopA loop of four stages. Stage one, take one task from the task queues (scripts, events, timers, messages) and run it on the call stack. Stage two, drain the entire microtask queue (promise callbacks, await continuations, queueMicrotask, MutationObserver), looping back to itself while new microtasks are added. Stage three, if a frame is due: requestAnimationFrame callbacks, style, layout, paint. Stage four, if idle: requestIdleCallback. Then back to stage one. Side boxes show the task queue and microtask queue contents and the call stack.Task queuesclick handlersetTimeout cbfetch callbackMicrotaskspromise.thenawait resumequeueMicrotask1 · Run ONE taskto completion2 · Drain ALLmicrotasks3 · Frame due?rAF → style → layout → paint4 · idle → rICuntil empty
Figure 11.3. The event loop. One task, then all microtasks, then (if a frame is due) rAF → style → layout → paint, then idle callbacks. Everything on the main thread fits somewhere on this circle.

Promise vs. setTimeout ordering.

console.log('1');
setTimeout(() => console.log('4'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('2');
// 1, 2, 3, 4

The script is a task: prints 1 and 2, schedules a task (timeout) and a microtask (then). Task ends → drain microtasks → 3. Next task → 4.

await is a microtask boundary.

async function f() { console.log('b'); await null; console.log('d'); }
console.log('a'); f(); console.log('c');
// a, b, c, d

An async function runs synchronously until its first await; the rest is queued as a microtask.

An infinite microtask loop freezes the page.

function spin() { Promise.resolve().then(spin); }
spin(); // the microtask queue never empties

Step 2 never finishes, so the loop never reaches rendering or the next task. No frames, no clicks, nothing — the tab is frozen, exactly as with while(true){}. With setTimeout(spin, 0) instead, each call is a separate task, and the browser can render and handle input in between (slowly, but alive).

requestAnimationFrame runs right before rendering. It’s the right place to make visual changes for the next frame, and the wrong place for heavy computation (you’re spending the frame’s budget). rAF callbacks don’t run in background tabs.

setTimeout(fn, 0) isn’t zero. It’s “as a new task, after at least ~0 ms,” subject to clamping (nested timeouts get clamped to ≥4 ms) and to whatever else is queued.

Since a task runs to completion, a 300 ms task means:

  • no frames for 300 ms (anything main-thread-driven freezes),
  • no input handling for 300 ms (taps wait — input delay, INP).

The fix isn’t “make it faster” (though that helps); it’s break it up and yield — let the event loop breathe between chunks so input and rendering can happen.

Long task vs yielded chunksTop: one red 300 millisecond task; a tap arriving early waits until the end. Bottom: ten 30 millisecond chunks separated by gaps; the tap handler runs in the first gap after it arrives, and frames render between chunks.No yieldone 300 ms tasktaphandled ~270 ms laterYieldtap handled in the next gap
Figure 11.4. Yielding. One 300 ms task blocks a tap for up to 300 ms. The same work in 30 ms chunks with yields lets the tap run between chunks.

How to yield:

  • scheduler.yield() — await scheduler.yield() inside a loop pauses your function, lets the browser handle pending input and render, then resumes your function with priority (ahead of other queued tasks, so you don’t lose your place). Supported in Chromium and rolling out elsewhere; feature-detect and fall back.
  • setTimeout(…, 0) — the classic fallback: split work into chunks, schedule the next chunk as a new task. Works everywhere; the continuation goes to the back of the queue.
  • scheduler.postTask(fn, { priority }) — schedule tasks with user-blocking, user-visible or background priority.
  • isInputPending() — an earlier Chromium experiment to check “is there input waiting?” and yield only then. Superseded in practice by scheduler.yield().
  • Framework-level: React’s concurrent rendering (startTransition, useDeferredValue) splits rendering into interruptible work and yields to the browser.
async function processAll(items) {
for (let i = 0; i < items.length; i++) {
process(items[i]);
if (i % 50 === 0) await yieldToMain(); // let input and frames through
}
}
const yieldToMain = () =>
globalThis.scheduler?.yield ? scheduler.yield() : new Promise((r) => setTimeout(r, 0));

A good mental rule: inside an event handler, do the minimum needed to update the UI, paint, then do the rest. Update the button’s state first; yield; then send analytics, recompute derived data, and so on.

When work doesn’t need the DOM, move it to another thread.

  • Dedicated Web Workers — a separate thread with its own JS heap and event loop. No DOM access. Talk via postMessage. Ideal for parsing large JSON, search indexing, image processing, diffing, crypto.
  • SharedWorkers — one worker shared by multiple tabs of the same origin (support is uneven, notably on mobile).
  • Service Workers — a special worker that sits between your page and the network, intercepting fetches; it powers offline and caching (Chapter 12). Not for general computation.
  • Worklets — tiny, specialized scripts hooking into the rendering pipeline (Paint Worklet, Audio Worklet, Animation Worklet).
  • OffscreenCanvas — lets a worker own a canvas and render to it (2D or WebGL) entirely off the main thread. Excellent for continuous canvas animations (Chapter 20) — and directly relevant to a “wallpaper canvas” that shouldn’t compete with UI work.

The cost of postMessage, and how to avoid it

Section titled “The cost of postMessage, and how to avoid it”

Messages between threads are copied using the structured clone algorithm. Sending a 50 MB object means serializing and deserializing 50 MB — on the main thread, on both ends. Two escapes:

  • Transferables: pass ArrayBuffers (and ImageBitmap, OffscreenCanvas, MessagePort) in the transfer list. Ownership moves instantly, zero copy; the sender’s copy becomes unusable.
  • SharedArrayBuffer: memory genuinely shared between threads, coordinated with Atomics. Because shared memory enables high-resolution timers (and thus Spectre-style attacks, Chapter 8), it’s only available on cross-origin isolated pages, which send two headers: Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp (or credentialless). Those headers have consequences: every cross-origin resource you embed must opt in, which can break third-party embeds.
postMessage copy, transfer, shareThree rows between a main thread box and a worker box. Copy: data is serialized and duplicated, red cost bar. Transfer: an ArrayBuffer moves across instantly, the main thread’s copy becomes empty. Share: both threads point at one SharedArrayBuffer, with a note requiring COOP and COEP headers.MainWorkercopy (structured clone)serialize + deserialize: O(size)transfer (ArrayBuffer)instant; sender’s copy detachedshare (SharedArrayBuffer)needs COOP + COEP (cross-origin isolated)
Figure 11.5. Copy vs. transfer vs. share. Structured clone copies (cost grows with size); transfer moves ownership instantly; SharedArrayBuffer shares memory but requires cross-origin isolation.

The search box that froze on every keystroke. A team filters a 20,000-item list on every input event, synchronously, re-rendering the whole list. Each keystroke is a 150–300 ms task on mid-range phones; characters appear in bursts. Fixes, in order of impact: virtualize the list, debounce or use useDeferredValue so typing stays responsive, move filtering to a worker with a prebuilt index.

The SPA that slowly died. An analytics dashboard leaks a chart instance on every route change (a resize listener held a reference). After an hour of use, the heap is 1.5 GB; GC pauses are constant; the tab crashes on low-memory laptops. A heap snapshot comparison finds thousands of detached canvases retained by window’s resize listeners. One cleanup function fixes it.

You can explain V8’s parse → bytecode → tiered JIT pipeline and deoptimization; why JS bytes cost more than image bytes; how generational GC works and how to hunt leaks with heap snapshots; draw the event loop and solve ordering puzzles from one rule; explain why an infinite microtask chain freezes a page; yield with scheduler.yield() and friends; and choose between workers, transferables and SharedArrayBuffer with their costs in mind.

1. What runs first: a setTimeout(…, 0) callback or a resolved promise’s .then?

The .then (microtask) — microtasks drain before the next task.

2. Why does lazy parsing help startup?

Functions not called during startup are only pre-parsed, saving full parse and compile time until (if ever) they’re called.

3. What is a detached DOM node leak?

An element removed from the document but still referenced from JS, keeping it (and its subtree) in memory.

4. Where in the loop do rAF callbacks run?

In the rendering steps, just before style/layout/paint for a frame.

5. What does scheduler.yield() do better than setTimeout(0)?

Resumes your continuation with priority instead of at the back of the task queue, while still letting input and rendering run.

6. Why does SharedArrayBuffer need cross-origin isolation?

Shared memory enables high-precision timers usable for Spectre-style attacks; isolation ensures no cross-origin data shares the process unless it opted in.

Warm-up 1. Predict.

setTimeout(() => console.log('A'), 0);
queueMicrotask(() => console.log('B'));
(async () => { console.log('C'); await 0; console.log('D'); })();
Promise.resolve().then(() => console.log('E'));
console.log('F');
Solution

C, F, B, D, E, A. (Sync: C, F. Microtasks in queue order: B, D (await continuation queued before E), E. Then task: A.)

Warm-up 2. Frozen or slow? Which freezes the tab and which merely makes it busy: (a) a recursive queueMicrotask chain, (b) a recursive setTimeout(fn, 0) chain?

Solution

(a) freezes — microtasks never drain. (b) busy but alive — rendering and input happen between tasks.

Warm-up 3. Read the GC. A trace shows dozens of “Minor GC” blocks during typing. What’s happening?

Solution

Lots of short-lived allocations per keystroke (new arrays/objects each filter). Reduce allocation or move the work off-thread.

Lab 4. Lumen’s search. Add client-side search over 10,000 fake essays to Lumen. Measure INP while typing on 4× throttle. Then yield in chunks, then move it to a worker. Compare.

Expected outcome

Synchronous: input lag and long tasks. Yielded: responsive input, results slightly later. Worker: responsive and fast, with message overhead for results.

Lab 5. Leak hunt. Add a component to Lumen that registers a resize listener without cleanup. Navigate between routes 20 times; use heap snapshots to find and fix the leak.

Hint

Compare snapshots; filter by “Detached”; follow the retainer path to window → listener.

Lab 6. Transfer vs copy. Send a 50 MB ArrayBuffer to a worker by copy and by transfer; time both with performance.now().

Expected outcome

Copy takes tens of milliseconds or more; transfer is near-instant, and the sender’s buffer has byteLength 0 afterwards.

Lab 7. Bundle cost on a phone. Using the Coverage tab and the Performance panel, find how much of Lumen’s JS is unused on initial load and how long its evaluation takes at 4× throttle.

Hint

Coverage shows unused bytes per file; Evaluate Script blocks in the trace show execution cost. Both feed Chapter 18’s plan.

Staff 8. The “it’s just 100 KB” argument. A teammate argues that adding a 100 KB (gzipped) charting library to the homepage is fine “because images are bigger.” Write the counter-argument.

Model answer

Compressed 100 KB is ~300–500 KB of JS to parse, compile and execute on the main thread; on a mid-range phone that’s hundreds of ms of blocked input, unlike an image decoded off-thread. Load it only on the route/interaction that needs it, or choose a lighter alternative.

Staff 9. Explain to a PM. In five sentences, explain why “the button sometimes takes a second to react” can happen even when the server is fast.

Model answer

The browser has one main worker for the page; if it’s busy with a big chunk of work, a tap waits in line. Our page does a large chunk of work right after loading and when lists update. The server isn’t involved; the phone’s processor is. We’ll split that work into small pieces so taps can jump the queue. We’ll measure it with the INP metric before and after.