Skip to article content
FrontendXLesson 14 / 20

Memory leaks

Turn a vague failure report into a reproduction, isolate the cause, form and falsify hypotheses, instrument the code, fix async and state bugs, lock the fix behind a regression test and review changes for real trade-offs.

intermediate · about 40 minutes · 2 exercises

  • Explain
  • Debug

What you will be able to do

#
  • Recognise the common shapes of a leak: listeners, timers, subscriptions and unbounded caches.
  • Use repeated snapshots to prove that memory is retained after an action.

Overview

#

A memory leak is memory that stays reachable after it should be collectable. The garbage collector cannot free an object while something still references it, so a leak is a reference you forgot to release.

The first shape is an event listener that is added but never removed. The listener keeps its closure, and the closure keeps everything it captured alive for as long as the target lives.

snippet.js
function mountPanel(button, onOpen) {
  window.addEventListener('resize', () => onOpen());
  button.addEventListener('click', onOpen);
}

When the panel is removed, both listeners remain. The fix is symmetric cleanup: every add has a matching remove with the same function reference, and a fetch has an AbortController.

snippet.js
function mountPanel(button, onOpen) {
  const onResize = () => onOpen();
  window.addEventListener('resize', onResize);
  button.addEventListener('click', onOpen);
  return () => {
    window.removeEventListener('resize', onResize);
    button.removeEventListener('click', onOpen);
  };
}

The second shape is a timer. setInterval holds its callback and everything the callback captures until it is cleared. A timer started on mount and never cleared keeps running and keeps its data alive.

The third shape is an unbounded cache. A Map keyed by request URL that grows forever is a leak even though every entry is small. Bound it with a maximum size or use a WeakMap keyed by an object so entries are collectable with their key.

The fourth shape is a detached DOM node. A node removed from the document but still referenced by a variable or a listener is retained, and so is its subtree.

To prove a leak, take a heap snapshot, perform the action that is suspected, force collection, take a second snapshot and compare retained sizes. Repeat the action several times: if the count of a component's instances grows with each repetition and never falls, the reference is not released. A single snapshot proves nothing; the trend across repetitions is the evidence.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Debug

    This code starts an interval that reads a large report object and never stops it, so the report stays reachable after the widget is closed. Fix it so the caller can stop the timer and release the data.

    starter.javascript
    function startPolling(report, render) {
      setInterval(() => render(report.rows), 1000);
    }

    Reveal the reference answer
    reference.javascript
    function startPolling(report, render) {
      const timer = setInterval(() => render(report.rows), 1000);
      return () => clearInterval(timer);
    }

    Authored expected output: startPolling returns a stop function; calling it clears the interval so the callback and the report can be collected.

    The original discards the timer id, so nothing can clear the interval. The callback keeps report reachable forever. Returning a stop function makes cleanup possible and symmetric with the start.

  2. Exercise 2Explain

    Give a review rubric for finding a memory leak in a long-lived page, including how you would prove the leak rather than guess it.

    Reveal the reference answer
    reference.text
    Check the four shapes in order: listeners that are added without a matching remove, timers that are started without being cleared, subscriptions and observers that are never unsubscribed, and caches or registries that grow without a bound. For each, look for the symmetry between setup and teardown. To prove a leak, take a heap snapshot, perform the suspected action, force collection and take a second snapshot, then repeat the action several times and watch whether the retained count of the component's instances grows and never falls. The trend across repetitions is the evidence; a single snapshot is not.

    Authored expected output: A rubric covering listeners, timers, subscriptions and unbounded caches, plus a repeated-snapshot procedure that proves retention.

    Leaks share a small set of shapes, so a checklist finds them faster than reading everything. Retention is proven by a growing count across repeated actions, because one snapshot cannot separate a real leak from normal allocation.

Common misconceptions

#
  • A small object cannot cause a leak.
  • A leak is visible immediately rather than after repeated actions.

Follow-up practice

#
  • debugging-review-15-network-and-offline

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.