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 |
- The widget is gone, but one scroll runs 5 handlers. The work is repeated, and if the handler changes state, the result can get strange.
- Each handler is a closure: a function that remembers the variables from where it was created. Here each handler remembers
rows, so 5 arrays of 1,000 rows are held in memory too. The garbage collector (the part of JavaScript that throws away data nobody uses any more) isn't allowed to remove them while the listener is registered.
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.
- If a listener was added with
{ capture: true }, it must be removed with{ capture: true }as well. - Calling
addEventListenertwice with the same type and the same function doesn't make two listeners. The browser keeps just one.
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
new AbortController()makes a controller that has asignal.{ signal: controller.signal }ties the listener to that signal. An arrow function is safe here, because the signal does the removing, not a function reference.controller.abort()removes every listener tied to that signal.- For a listener that only needs to run once, there is
{ once: true }: the browser removes it by itself after the first call. - One note on this example: the browser sends the
resizeevent only towindow, so aresizelistener on an element such aspagenever runs. For the size of an element, useResizeObserver.
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)
},
}
}
onreturns anunsubscribefunction. That function remembershandlerthrough a closure, sofilter((h) => h !== handler)removes only that one.listeners[event] || []keeps an event that was never registered safe:count("hover")is 0, andemit("hover")is 0 too.emitreturns how many handlers it called.leakReport(10)returns the names of events with 10 or more listeners. Node.js has a similar alarm:EventEmittergives aMaxListenersExceededWarningwhen one event has more than 10 listeners.
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
- Elements, select the element, then the Event Listeners tab beside it: the listeners attached to that element.
- Console:
getEventListeners(window)shows the listeners per type. This function only exists in the DevTools Console, you can't use it in app code. - Performance monitor (in the More tools menu): a "JS event listeners" graph that keeps climbing as you go back and forth between pages is a sign of a leak.
- Memory, heap snapshot: take a snapshot, do the interaction and then return to the starting state (open and close the widget), take a second snapshot, then choose the Comparison view. If objects from that interaction are still retained and their number grows each time you repeat it, a listener or a closure is holding them. This is the clearest sign.
⚠️ Why won't the listener let go?
- A new arrow function in
removeEventListener. No error, nothing removed. Keep the function in a variable, or useAbortController. - An unsubscribe that empties everything. In the exercise,
off1()may only remove the first handler.listeners[event] = []makescount("click")0, when it should be 1. - Forgetting events that don't exist yet.
listeners["hover"].lengththrows aTypeErrorifhoverwas never registered. Uselisteners[event] || []. - Other subscriptions nobody stops.
setIntervalneedsclearInterval,IntersectionObserverneedsdisconnect(), a WebSocket needsclose(). Same pattern: what you set up on mount, you tear down on unmount.
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.