Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Debugging Workflows

Finding Memory Leaks

A hands-on workflow for memory leaks: spot growth with the Performance monitor, reproduce it, compare heap snapshots, read retainers and fix listeners, timers and detached DOM.

A page that is fast at first and slower after twenty minutes, a single-page app whose tab grows to a gigabyte, a dashboard that crashes with "Aw, Snap!": these are leak symptoms. This lesson ties the Memory panel knowledge from the earlier chapter into a debugging workflow, and shows the five most common leak patterns with the fix for each.

Step 1: confirm it is a leak

Not every growing graph is a leak. Memory legitimately grows while you load data, then drops when the garbage collector runs. A leak is a staircase that never comes back down when you repeat the same action.

Open the command menu (Ctrl+Shift+P), run Show Performance monitor, and watch JS heap size, DOM Nodes and JS event listeners. Perform the suspicious action (open and close a modal, navigate to a view and back) ten times. If the lines climb with each repetition, and a forced GC (the trash can in the Memory panel) does not return them to the old level, you have a leak. DOM Nodes and listeners rising are strong hints about the cause.

Step 2: isolate and snapshot

Use the three-snapshot method: warm up once, force GC, snapshot; repeat the action N times, force GC, snapshot; repeat again, force GC, snapshot. In the last snapshot use Comparison against the previous one and look for objects with a # New close to N and few deleted. Select one, read the Retainers pane and follow it to the first reference that is yours.

The five usual suspects

1. Event listeners that are never removed

JavaScript
function openPanel() {
  const panel = document.createElement("div");
  document.body.append(panel);
  window.addEventListener("resize", () => layout(panel));   // leak: window keeps panel alive
}

Each call adds a listener on window whose closure keeps panel alive even after the panel is removed. Fix with a named handler and removeEventListener on close, or an AbortController signal: addEventListener("resize", fn, { signal }) and controller.abort() when done.

2. Timers

A setInterval keeps running and keeps its closure alive until clearInterval is called. Clear timers when a component unmounts.

3. Detached DOM nodes

If you remove an element from the page but keep it in a variable, array or Map, the whole subtree stays in memory. In the heap snapshot, filter by "Detached" to list them.

4. Unbounded caches and logs

An object used as a cache that never evicts, an array of every message ever received, or an undo history with no limit grow without bound. Use a size limit, an LRU policy, or a WeakMap when the key is an object.

5. Closures capturing large objects

A small callback can hold a large object through its closure scope. Set references to null when done, or avoid capturing the big object in the first place.

Simulating the leak and the fix

You cannot see a real heap in this sandbox, so the stand-in below simulates the pattern with a registry of "listeners" on a fake window, which is the same reference chain a heap snapshot's Retainers pane would show.

JS Stand-in: a listener leak and its fix

Press Run (or Ctrl + Enter) to see the console output here.

No output.

After ten open-close cycles the leaky version still has ten listeners, each holding a 1000-element array alive, even though no panel is visible. The fixed version returns to zero. This matches what the Performance monitor shows as a rising "JS event listeners" line.

A bounded cache

For the caching case, a least-recently-used (LRU) limit stops unbounded growth. The Map keeps insertion order, which makes a small LRU easy.

JS Stand-in: unbounded cache versus LRU cache

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 3: verify the fix

Repeat the Performance monitor test: the heap line should now saw-tooth around a constant level while you repeat the action. Take a final comparison snapshot to confirm the leaked constructor no longer grows. Add a regression guard if you can, for example a test that opens and closes a component 100 times and asserts that the number of listeners returns to the start.

Remember that modern frameworks clean up for you only if you use their lifecycle: in React return a cleanup function from useEffect, in Vue use onUnmounted, in Angular use ngOnDestroy or takeUntilDestroyed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Performance monitor line rising with every open-close of a modal strongly suggests a listener leak?

    Each uncleaned addEventListener call increases the listeners count.
  2. 2. What does a red (detached) object in a heap snapshot usually mean?

    Detached DOM trees are kept in memory by a reference somewhere, which is a common leak.
  3. 3. How can you automatically remove event listeners when work is finished?

    Passing { signal } lets one abort() call remove all listeners registered with that signal.
  4. 4. Why use a WeakMap for per-object metadata?

    WeakMap does not prevent its keys from being collected, so it does not leak the keys' entries.

Summary

  • A leak is memory that keeps growing after repeated actions and forced GC.
  • Use the Performance monitor to confirm, snapshots and Comparison to find, Retainers to explain.
  • Usual causes: listeners, timers, detached DOM, unbounded caches, closures.
  • Fix with cleanup functions, AbortController, LRU limits and WeakMap; verify with a second measurement.

Next: Debugging Network and CORS Failures