04 · Browser & Web Platform
mediumdebuggingjavascript~8 min

Fix the Listener Leak

Objective: Spot the classic cleanup leak and fix it with a returned disposer.

`createBus` lets components subscribe, but `on` never gives them a way to unsubscribe, so handlers pile up after components unmount. Make `on` return an unsubscribe function.

  • `on(type, fn)` returns a function that removes exactly that subscription.
  • Calling the disposer twice is safe.
  • `emit` keeps calling remaining handlers in subscription order.
  • The same function subscribed twice is removed one subscription at a time.
JavaScript

⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor

Output
> Nothing has run yet.
Interview follow-up questions
  • How does AbortController's signal option on addEventListener help here?
  • How would you find a leaked listener in Chrome DevTools?
  • What leaks if a handler closes over a large DOM tree?