Skip to content

Browser Memory Leak

Quick summary

Your web page gets slower over time because JavaScript is holding references to objects that should be garbage collected.

Why this happens

  • Event listeners not removed when elements are removed from the DOM

  • Intervals and timeouts not cleared when no longer needed

  • Closures holding references to large objects unnecessarily

  • Global variables accumulating data without cleanup

Minimal example

✗ Broken code
function setup() {
  const el = document.querySelector(".btn");
  el.addEventListener("click", () => {
    console.log("clicked");
  });
  // If el is removed from DOM, the listener and closure persist
  // Memory leak: el and its closure are never garbage collected
}
✓ Fixed code
function setup() {
  const el = document.querySelector(".btn");
  const handler = () => console.log("clicked");
  el.addEventListener("click", handler);
  // Return a cleanup function
  return () => el.removeEventListener("click", handler);
}
// Call cleanup when the element is removed

Store the handler reference and return a cleanup function that removes the event listener. Call cleanup when the element is removed from the DOM to prevent the memory leak.

How to diagnose

  • Use DevTools Memory tab — take heap snapshots and compare

  • Use the Performance Monitor to watch JS heap size over time

  • Look for detached DOM nodes in the heap snapshot

How to fix

  • Remove event listeners with removeEventListener when elements are removed

  • Clear intervals and timeouts with clearInterval/clearTimeout

  • Set references to null when no longer needed

  • Use WeakMap/WeakSet for references that should not prevent garbage collection

How to prevent

  • Always clean up event listeners, intervals, and timeouts

  • Avoid global variables — use modules and closures properly

  • Use weak references for data that can be garbage collected

Related Resources

Related Glossary

Related Lessons

← Back to language