Event Listener and Closure Leaks — Debugging

A listener that isn't removed keeps running and holds all the data in its closure, so mounting and unmounting 5 times without cleanup leaves 5 listeners…

You move house but forget to cancel your newspaper subscription, so the paper keeps arriving at the old address every morning. Move five times without cancelling, and five papers get delivered for nothing every morning.

An event listener can end up the same way. A listener is a function you register on an element so the browser calls it when something happens, such as a click or a scroll. It leaks when it stays registered after the part of the page that needed it is gone: it still runs on every event, and all the data it holds can't be removed from memory.

The listener that stays behind

In a single page app (SPA), components are mounted and unmounted all the time as the user moves between pages. The page itself never reloads, so a listener attached to page (in a real app usually window or document) stays there for as long as the tab is open.

const page = document.getElementById("page")

function mountWidget() {
  const rows = new Array(1000).fill("row") // the widget's data
  page.addEventListener("scroll", () => {
    console.log("scroll", rows.length)
  })
  // nothing removes the listener
}
Event Widget on screen Active listeners Handlers run per scroll
mount #1 yes 1 1
unmount #1 gone 1 1
mount + unmount 5 times gone 5 5

Now the widget gets a cleanup. Each time it's removed, it runs page.removeEventListener("scroll", () => ...) with an arrow function rewritten exactly as it was when added. If it's added and removed 5 times, guess: how many listeners are still active?

Remove it with the same function

removeEventListener looks for a listener with the same type and exactly the same function (the same reference, not the same contents). Two arrow functions written the same way are still two different functions.

// Bug: the arrow function in remove is a new function
page.addEventListener("scroll", () => console.log("scroll"))
page.removeEventListener("scroll", () => console.log("scroll")) // removes nothing

// Right: keep the function in a variable, use it to add and to remove
const handler = () => console.log("scroll")
page.addEventListener("scroll", handler)
page.removeEventListener("scroll", handler) // removed

So the widget with that cleanup still leaves 5 listeners active. removeEventListener finds no matching function, and it doesn't throw an error either, so the bug is silent.

AbortController: one switch to remove them

The modern, shorter way: add the listener with a signal, then call abort() to remove them all at once.

function mountWidget() {
  const controller = new AbortController()
  const rows = new Array(1000).fill("row")

  const options = { signal: controller.signal }

  page.addEventListener("scroll", () => console.log("scroll", rows.length), options)
  page.addEventListener("resize", () => console.log("resize"), options)

  return () => controller.abort() // the unmount function: removes both
}

const unmount = mountWidget()
unmount() // active listeners back to 0

In React: cleanup in useEffect

The function returned from useEffect is the cleanup. React runs it when the component unmounts, or before the effect runs again because a dependency changed.

function ScrollInfo() {
  useEffect(() => {
    const handler = () => console.log(window.scrollY)
    window.addEventListener("scroll", handler)
    return () => window.removeEventListener("scroll", handler) // the same reference
  }, [])

  return <p>Scroll this page</p>
}

In development mode with <StrictMode>, React deliberately runs setup, cleanup, then setup again when the component first mounts. If the cleanup is missing, the listener doubles right away, so the bug shows up sooner.

Count the listeners yourself

Ordinary code has no way to ask the browser "how many listeners does this element have?". So many libraries count them themselves, exactly what you build in the exercise: a small event emitter that keeps listeners per event name.

function createEmitter() {
  const listeners = {} // { click: [handlerA, handlerB], scroll: [...] }

  return {
    on(event, handler) {
      if (!listeners[event]) listeners[event] = []
      listeners[event].push(handler)
      return () => { // unsubscribe: remove this handler only
        listeners[event] = listeners[event].filter((h) => h !== handler)
      }
    },
    emit(event, payload) {
      const list = listeners[event] || []
      list.forEach((h) => h(payload))
      return list.length
    },
    count(event) {
      return (listeners[event] || []).length
    },
    leakReport(threshold) {
      return Object.keys(listeners).filter((event) => listeners[event].length >= threshold)
    },
  }
}

With the exercise's starter code: two on("click") and one on("scroll") make count("click") 2, count("scroll") 1, count("hover") 0, and emit("click") 2. After off1(), count("click") becomes 1. Add 15 scroll listeners, and count("scroll") becomes 16, so leakReport(10) holds one name: scroll.

How to check in Chrome DevTools

⚠️ Why won't the listener let go?

TL;DR: A listener that isn't removed keeps running and holds all the data in its closure, so mounting and unmounting 5 times without cleanup leaves 5 listeners. removeEventListener only removes exactly the same function (the same reference, the same capture), so keep the handler in a variable. AbortController removes every listener that uses its signal with one abort(). In React, remove listeners in the cleanup function that useEffect returns. To count listeners, keep them yourself per event name: on returns an unsubscribe that removes only that handler, count and emit are safe for an empty event, and leakReport(threshold) names the events whose listeners reach the threshold. In DevTools, a heap snapshot whose retained objects keep growing after the interaction is reset is the clearest sign of a leak.

⚡ The listener that stays behind

Meaning: In an SPA, components come and go, but the page never reloads. A listener that isn't removed keeps running on every event and holds the data in its closure. Mount and unmount 5 times without cleanup, and 5 listeners are active.

⚡ Remove it with the same function

Write:

// Bug: the arrow function in remove is a new function
page.addEventListener("scroll", () => console.log("scroll"))
page.removeEventListener("scroll", () => console.log("scroll")) // removes nothing
Guess first: is the listener removed?

No. Two arrow functions written the same way are still two different functions. removeEventListener needs exactly the same reference, and it throws no error, so the bug is silent.

Meaning: Keep the function in a variable, then use that variable to add and to remove.

⚡ AbortController: one switch to remove them

Write:

const options = { signal: controller.signal }

page.addEventListener("scroll", () => console.log("scroll", rows.length), options)
page.addEventListener("resize", () => console.log("resize"), options)

Meaning: controller.abort() removes every listener tied to that signal at once.

⚡ In React: cleanup in useEffect

Write:

useEffect(() => {
  const handler = () => console.log(window.scrollY)
  window.addEventListener("scroll", handler)
  return () => window.removeEventListener("scroll", handler) // the same reference
}, [])

Meaning: The function returned from useEffect is the cleanup. React runs it when the component unmounts.

What you will learn