Track 02 · Lesson 6 of 17Inside the browser

Track 02 · Inside the browser

Listener options and cleanup

Lesson 6 of 17· 7 min

addEventListener takes options that change how a listener behaves, and every listener you add should eventually be removed, or it keeps running, and holding memory, after you no longer need it.

Subscribe, unsubscribe

Three options, three panels

once and removeEventListener

0 times the handler ran. Listener attached.

AbortController: remove many at once

Not listening

0 listeners active. Pointer moves: 0, clicks: 0.

passive: let scrolling start immediately

The listener below calls preventDefault() on every wheel and touch-move event. Scroll inside the box with each setting.

Scroll me with a mouse wheel, trackpad or finger.

You scrolled down here.

The end.

Non-passive listener attached. Try scrolling the box.

button.addEventListener("click", claim, { once: true });
button.removeEventListener("click", claim); // needs the same function

const controller = new AbortController();
pad.addEventListener("pointermove", onMove, { signal: controller.signal });
pad.addEventListener("click", onClick, { signal: controller.signal });
controller.abort(); // removes both

window.addEventListener("scroll", onScroll, { passive: true });

// React: clean up in useEffect
useEffect(() => {
  const controller = new AbortController();
  window.addEventListener("resize", onResize, { signal: controller.signal });
  return () => controller.abort();
}, []);

Removing a listener#

removeEventListener needs the same function you added. Passing a fresh arrow function that looks identical does nothing, because it's a different function. That's why the demo keeps one stable handler.

An AbortController avoids that bookkeeping. Pass its signal to as many listeners as you like, then call abort() once to remove them all. The same signal also cancels fetch requests, so one cleanup can stop everything a component started.

passive: true#

The browser can't start scrolling until it knows whether your wheel or touch listener will call preventDefault(). A passive listener promises it won't, so scrolling starts immediately. Unless you truly need to cancel scrolling, mark scroll, wheel and touch listeners passive.

Check yourself

You added a listener with addEventListener(“click”, () => save()). Why does removeEventListener(“click”, () => save()) fail to remove it?