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.
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:
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.
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.
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.
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)runscbjust before the next frame is painted. Use it for visual updates and animations driven by JavaScript. It pauses in background tabs.requestIdleCallback(cb)runscbwhen 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 tosetTimeout.scheduler.yield()returns a promise that resumes your code after the browser has had a chance to handle input and render. UnlikesetTimeout(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:
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:
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:
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.
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);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:
IntersectionObservercalls 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 theimgdoes it without code.ResizeObservercalls you when an element's size changes, which windowresizeevents 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
windowresizelistener on mount and never removes it. The listener's closure keeps the component's state alive, and every remount adds another. - Timers. A
setIntervalkeeps 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
Mapused as a cache, keyed by URL or ID, that grows forever.
The panel is in the page and in an openPanels array your code keeps for bookkeeping.
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:
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 each leak to its fix.
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:
- Load the page, do the action once to warm up caches, and take a heap snapshot.
- Do the action and undo it several times (open and close the modal ten times).
- 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 the steps of hunting a suspected leak in order.
- Tap the steps below in the right order.
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:
| Metric | Measures | Good | Poor |
|---|---|---|---|
| LCP (Largest Contentful Paint) | When the main content appears | 2.5 s or less | over 4 s |
| INP (Interaction to Next Paint) | How quickly the page responds to input, across the visit | 200 ms or less | over 500 ms |
| CLS (Cumulative Layout Shift) | How much content jumps around | 0.1 or less | over 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 (
widthandheight), 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".
- 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.