Skip to content

Lesson 33 of 50JavaScript at work

Performance and Memory in the Browser

Find and fix slow interactions and memory leaks: the rendering pipeline, long tasks, workers, observers, garbage collection, DevTools and Core Web Vitals.

24 min read0/4 questions

The product team says the dashboard "feels sluggish". Typing in the filter box lags, scrolling stutters after you open a few reports, and after an hour in a tab the whole thing is noticeably slower than on a fresh load. None of this shows up in a quick test on your fast laptop. It shows up in real-user data as a poor INP score, and in support tickets from people on mid-range phones. Fixing it needs two skills: knowing what the browser does between your code running and pixels appearing, so you can keep the main thread free, and knowing how memory is reclaimed, so you can find what stops it being reclaimed. The Event Loop lesson showed that rendering waits for your task to finish. This lesson shows what that costs and what to do about it.

What happens in a frame

The main thread runs your JavaScript and most of the browser's rendering work. When something on screen changes, the browser runs a pipeline:

The rendering pipeline
  1. JavaScriptyour handlers, timers, framework renders
  2. Stylework out which CSS rules apply to each element
  3. Layoutcompute every box's size and position
  4. Paintrecord drawing commands for each layer
  5. Compositecombine layers on the GPU into the final frame

Changing width, top or font size changes geometry, so the browser runs every stage. Layout is often the expensive one, and it can cover the whole page.

1/3

At 60 frames per second you have about 16.7 ms per frame, and on a 120 Hz screen about 8.3 ms, for all of that plus your code. The browser also needs some of that budget for itself, so in practice your JavaScript per frame should be a few milliseconds.

Layout thrashing

Normally the browser is lazy: you change styles, it marks layout as stale, and recalculates once before the next frame. But if you read a geometry property (offsetWidth, offsetTop, getBoundingClientRect(), scrollTop, getComputedStyle()) after a write, the browser must run layout right now to give you a correct answer. This is a forced synchronous layout. Do it in a loop, write, read, write, read, and you get layout thrashing: one full layout per iteration.

Run this, then press each button a few times. Both versions set the same widths on the same 1,000 elements.

HTML & CSS
<style> body { font-family: system-ui, sans-serif; margin: 12px; } button { padding: 6px 12px; margin-right: 8px; } #out { font-family: ui-monospace, monospace; margin: 12px 0; white-space: pre; } #boxes { display: flex; flex-wrap: wrap; gap: 2px; } .box { height: 6px; background: #6b7280; }</style><button id="bad">Interleaved reads and writes</button><button id="good">Batched: read once, then write</button><div id="out">Click a button. Each run resizes 1,000 boxes.</div><div id="boxes"></div> <script> const boxes = document.getElementById("boxes"); const out = document.getElementById("out"); for (let i = 0; i < 1000; i++) { const box = document.createElement("div"); box.className = "box"; boxes.append(box); } const els = [...boxes.children]; let frac = 0.05; function interleaved() { for (const el of els) { // Read (forces layout, because the last write made it stale), then write const width = boxes.offsetWidth; el.style.width = width * frac + "px"; } } function batched() { const width = boxes.offsetWidth; // one read, one layout for (const el of els) el.style.width = width * frac + "px"; // writes only } function time(label, fn) { frac = frac === 0.05 ? 0.03 : 0.05; // change something real each run const start = performance.now(); fn(); boxes.offsetWidth; // include the final layout in both timings const ms = performance.now() - start; out.textContent = `${label}: ${ms.toFixed(1)} ms\n` + out.textContent.split("\n").slice(0, 4).join("\n"); } document.getElementById("bad").addEventListener("click", () => time("interleaved", interleaved)); document.getElementById("good").addEventListener("click", () => time("batched ", batched));</script>

Preview

On a typical laptop the interleaved version takes over a hundred times longer, and the batched one is a couple of milliseconds. The fix is always the same shape: do all your reads first, then all your writes. When reads and writes come from different components, schedule the writes with requestAnimationFrame so they happen together just before the next frame. In DevTools, forced layouts show up as purple "Layout" blocks with a warning triangle inside your JavaScript.

Quick check
Which loop causes layout thrashing?
Need a nudge? A hint rules out a wrong answer.

Keep the main thread free

While your code runs, the browser cannot respond to input or paint. A task longer than 50 ms is a long task, and long tasks are the main cause of laggy clicks and typing.

Scheduling tools

  • requestAnimationFrame(cb) runs cb just before the next frame is painted. Use it for visual updates and animations driven by JavaScript. It pauses in background tabs.
  • requestIdleCallback(cb) runs cb when the browser has spare time, with a deadline telling you how much. Good for low-priority work like sending analytics or prefetching. Not every Safari version has supported it, so feature-detect and fall back to setTimeout.
  • scheduler.yield() returns a promise that resumes your code after the browser has had a chance to handle input and render. Unlike setTimeout(0), the continuation goes to the front of the queue, so other scripts cannot jump ahead of your remaining work. Support is not universal yet; feature-detect it.

The core technique is to break long work into chunks and yield between them. Total time goes up slightly, but a click that arrives mid-way gets handled within one chunk instead of waiting for everything:

JavaScript
function busy(ms) { const start = performance.now(); while (performance.now() - start < ms) {} // simulate heavy work} // Yield to the event loop. Browsers with scheduler.yield() resume your task// ahead of other queued tasks; the setTimeout fallback works everywhere.function yieldToMain() { if (globalThis.scheduler?.yield) return scheduler.yield(); return new Promise((resolve) => setTimeout(resolve, 0));} async function run(label, work) { const t0 = performance.now(); let clickAt = null; // A "click" arrives 20 ms in. Its handler is a task that must wait its turn. setTimeout(() => (clickAt = performance.now() - t0), 20); await work(); const total = performance.now() - t0; await new Promise((r) => setTimeout(r, 30)); // make sure the click has landed console.log(`${label}: work took ${total.toFixed(0)} ms, click waited ${(clickAt - 20).toFixed(0)} ms`);} async function main() { // 1. One long task: 20 items x 15 ms = 300 ms with no break await run("one long task", async () => { for (let i = 0; i < 20; i++) busy(15); }); // 2. Same work, yielding between items await run("yielding ", async () => { for (let i = 0; i < 20; i++) { busy(15); await yieldToMain(); } });}main();
Output
Press Run (⌘ Enter) to see what happens.

The click waits nearly 300 ms in the first run and about one chunk in the second. In a real app, yield after doing the part the user needs to see (update the button state first, then yield, then do the analytics and the expensive recalculation).

Not all slow code should be chunked. Often the better fix is less work: debounce the filter input (Async Patterns covers debounce and throttle), render only visible rows of a long list (virtualisation), or let CSS skip off-screen content with content-visibility: auto.

Web Workers for CPU-heavy work

Some work is just big: parsing a 50 MB CSV, image processing, a search index, syntax highlighting. A Web Worker runs a script on a separate thread with its own event loop. It has no DOM access, and talks to the page only by messages:

main.ts
const worker = new Worker(new URL("./parse-worker.ts", import.meta.url), { type: "module" });
worker.postMessage({ file });          // the File is cloned to the worker
worker.onmessage = (e) => showRows(e.data.rows);

postMessage uses the structured clone algorithm: it deep-copies the data. For large binary data, transfer it instead. Transferring moves ownership of an ArrayBuffer to the other side in constant time, and the sender's copy becomes detached (zero length). The same rules apply to structuredClone, so you can see them here:

JavaScript
const pixels = new Uint8Array(8_000_000); // an 8 MB image bufferpixels[0] = 255; // Copying: what postMessage(data) does by default (structured clone)let t = performance.now();const copy = structuredClone(pixels);console.log(`clone: ${(performance.now() - t).toFixed(1)} ms, original still has ${pixels.byteLength} bytes`); // Transferring: move the underlying buffer instead of copying itt = performance.now();const moved = structuredClone(pixels, { transfer: [pixels.buffer] });console.log(`transfer: ${(performance.now() - t).toFixed(1)} ms, original now has ${pixels.byteLength} bytes`);console.log("moved[0] =", moved[0], "| copy[0] =", copy[0]);
Output
Press Run (⌘ Enter) to see what happens.

With a worker that is worker.postMessage(pixels, [pixels.buffer]). Workers are worth it when the work takes tens of milliseconds or more; for small jobs, copying data back and forth costs more than it saves. Libraries like Comlink wrap the message passing so a worker feels like an async function call.

Predict the outputJavaScript

What does this print?

const buf = new ArrayBuffer(16);
const view = new Uint8Array(buf);
const copy = structuredClone(view);
structuredClone(buf, { transfer: [buf] });
console.log(copy.byteLength, view.byteLength, buf.byteLength);
Need a nudge? Hints walk you through it.

Observers instead of polling

Scroll handlers that call getBoundingClientRect() on many elements are a classic cause of jank. The browser can tell you about geometry changes instead:

  • IntersectionObserver calls you when an element enters or leaves the viewport (or any scroll container). Use it for lazy loading, infinite scroll sentinels, "mark as read" and starting animations on view. For plain images, loading="lazy" on the img does it without code.
  • ResizeObserver calls you when an element's size changes, which window resize events miss (a sidebar opening, a container query layout). Charts and editors that must redraw on resize use it.

Both batch their callbacks and run them at the right point in the frame, so they do not cause layout thrashing on their own.

Memory: what the garbage collector can and cannot do

JavaScript frees memory automatically with a garbage collector (GC). The rule is reachability: starting from the roots (globals, the current call stack, the DOM tree, active timers and listeners), the GC follows every reference. Anything it cannot reach is garbage and gets freed. Anything it can reach is kept, whether or not you will ever use it again.

So a memory leak in JavaScript is never "forgot to free". It is "still reachable by accident". The usual suspects:

  • Detached DOM nodes. You remove an element from the page but a JavaScript variable, array or cache still points at it. The element and its whole subtree stay in memory.
  • Listeners and observers never removed. A component adds a window resize listener on mount and never removes it. The listener's closure keeps the component's state alive, and every remount adds another.
  • Timers. A setInterval keeps its callback, and everything the callback references, alive until cleared.
  • Closures capturing more than they need. A small callback that refers to one field of a huge response keeps the whole response reachable.
  • Unbounded caches. A Map used as a cache, keyed by URL or ID, that grows forever.
How a detached DOM node leaks
NamesObjects in memorydocumentopenPanelsDocumenthas #panelArray[panel]div#panel, 2,000 rows

The panel is in the page and in an openPanels array your code keeps for bookkeeping.

1/3

Cleanup patterns

Pair every "start" with a "stop" in the same place. AbortController makes this tidy, because one abort() removes every listener registered with its signal:

function mountPanel(panel: HTMLElement) {
  const controller = new AbortController();
  const { signal } = controller;
 
  window.addEventListener("resize", () => layout(panel), { signal });
  document.addEventListener("keydown", onKey, { signal });
  const timer = setInterval(refresh, 30_000);
  const observer = new ResizeObserver(() => layout(panel));
  observer.observe(panel);
 
  return function unmount() {
    controller.abort();      // removes both listeners
    clearInterval(timer);
    observer.disconnect();
    panel.remove();
  };
}

This is exactly what a React effect cleanup function is for. For caches, set a limit. A Map remembers insertion order, which makes a small least-recently-used cache easy:

JavaScript
// An unbounded cache is a memory leak with a nice name.// A Map remembers insertion order, which makes a small LRU cache easy.class LruCache { constructor(limit) { this.limit = limit; this.map = new Map(); } get(key) { if (!this.map.has(key)) return undefined; const value = this.map.get(key); this.map.delete(key); // move to the "most recent" end this.map.set(key, value); return value; } set(key, value) { this.map.delete(key); this.map.set(key, value); if (this.map.size > this.limit) { const oldest = this.map.keys().next().value; this.map.delete(oldest); } }} const unbounded = new Map();const lru = new LruCache(100);for (let i = 0; i < 50_000; i++) { const key = `/api/products?page=${i}`; const value = { items: new Array(20).fill(i) }; unbounded.set(key, value); lru.set(key, value);}console.log("unbounded entries:", unbounded.size);console.log("lru entries:", lru.map.size);console.log("oldest kept:", lru.map.keys().next().value);lru.get("/api/products?page=49900");console.log("after reading page 49900, oldest kept:", lru.map.keys().next().value);
Output
Press Run (⌘ Enter) to see what happens.

Weak references

When you want to attach data to an object without keeping the object alive, use a WeakMap. Its keys are held weakly: once nothing else references a key object, the entry disappears with it. That makes it the right tool for "extra data per DOM node" or "memoised result per object". The trade-off is that a WeakMap cannot be iterated or sized, because its contents depend on when the GC runs.

WeakRef and FinalizationRegistry go further: a reference that does not prevent collection, and a callback after an object is collected. Both are real but rarely the right answer. The GC gives no timing guarantees, a callback may never run, and engines differ. Use them for optional optimisations like caches of expensive objects, never for logic that must happen, such as closing a connection.

Match the pairs0/5 matched

Match each leak to its fix.

Choose an item, then its match on the other side.
How V8's garbage collector actually works

V8 (Chrome, Edge, Node) uses a generational collector, based on the observation that most objects die young. New objects go into a small young generation, collected often and cheaply by copying the few survivors elsewhere. Objects that survive a couple of these collections are promoted to the old generation, which is collected less often with a mark-and-sweep pass (plus compaction to reduce fragmentation).

Most of the marking runs concurrently on helper threads, and the remaining main-thread work is split into small incremental steps, so pauses are usually short. Short pauses are not free, though: code that allocates lots of short-lived objects in a hot loop (new arrays per frame, objects per mouse move) keeps the young-generation collector busy. In animation and game loops, reusing objects can remove visible stutter. Elsewhere, write clear code first and measure before optimising allocations.

Measuring with DevTools

Guessing about performance is usually wrong. Measure first.

Performance panel. Record while you do the slow interaction, ideally with CPU throttling on to imitate a mid-range phone. The main thread track shows a flame chart: wide bars are slow functions, and tasks with a red corner are long tasks. Look for purple layout blocks inside your JavaScript (forced layouts), and for one function dominating the "Bottom-up" view. Add performance.mark() and performance.measure() to your own code and the measures appear on the timeline.

Memory panel. For leaks, use the three-snapshot technique:

  1. Load the page, do the action once to warm up caches, and take a heap snapshot.
  2. Do the action and undo it several times (open and close the modal ten times).
  3. Take a second snapshot and use the Comparison view.

If the action is leak-free, the counts return to roughly the same level. If ten HTMLDivElement panels or ten copies of a component's state survived, you have found the leak. Type "Detached" in the class filter to list detached DOM trees, then select one and read its Retainers path: the chain of references from a root to that object tells you exactly which variable, listener or cache is holding on. The allocation timeline view shows when objects were allocated and which are still alive.

Put it in order5 steps

Put the steps of hunting a suspected leak in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Core Web Vitals from the JavaScript side

Google's Core Web Vitals are the three user-centred metrics most companies track, and they affect search ranking. Each is judged at the 75th percentile of real page loads:

MetricMeasuresGoodPoor
LCP (Largest Contentful Paint)When the main content appears2.5 s or lessover 4 s
INP (Interaction to Next Paint)How quickly the page responds to input, across the visit200 ms or lessover 500 ms
CLS (Cumulative Layout Shift)How much content jumps around0.1 or lessover 0.25

INP replaced First Input Delay in 2024, and it is the one JavaScript developers own most directly. It measures from the user's tap or key press until the next frame is painted, and it splits into three parts: input delay (a long task was already running), processing time (your handlers), and presentation delay (the style, layout and paint your handlers caused). Everything in this lesson so far reduces one of those parts.

From the JavaScript side:

  • LCP: do not render the main content only after a chain of client-side fetches; make the hero image discoverable in the HTML and give it high priority (fetchpriority="high"), and keep large scripts from blocking it.
  • INP: short handlers, yield after the visible update, no long tasks from third-party scripts during interaction, less DOM to lay out.
  • CLS: reserve space for images (width and height), ads and late content; never insert content above what the user is reading, except in response to their action.

Lab tools (Lighthouse, the Performance panel) are for diagnosis. Real users are the truth, so most teams collect field data with Google's small web-vitals library:

import { onCLS, onINP, onLCP } from "web-vitals";
 
function send(metric: { name: string; value: number; id: string }) {
  navigator.sendBeacon("/analytics", JSON.stringify(metric));
}
 
onCLS(send);
onINP(send);
onLCP(send);

Its attribution build adds which element and which script caused a slow result, which turns "INP is bad" into "the filter input's keydown handler takes 180 ms".

Key terms
forced synchronous layout
Reading geometry after a style change, making the browser compute layout immediately instead of once per frame.
long task
Any main-thread task longer than 50 ms; input and rendering must wait until it finishes.
Web Worker
A script on its own thread with no DOM access, talking to the page through postMessage.
transferable
An object such as an ArrayBuffer whose ownership moves to the receiver instead of being copied, detaching the sender's copy.
reachability
The garbage collector's rule: anything reachable from a root is kept, anything else is freed.
detached DOM node
An element removed from the page but still referenced from JavaScript, so it cannot be collected.
INP
Interaction to Next Paint: the delay from a user's input to the next painted frame, made of input delay, processing and presentation.