Skip to curriculum
Jump to the editor

25.1. Dispose listeners and subscriptions together

Easy
Topics

This question is in

25. Memory and cleanup
15–25 min

A widget that opens adds a resize listener to window, starts a polling interval, subscribes to a store and arms a timeout. When it closes, every one of those must be undone, or the page keeps running code for a widget nobody sees, and keeps its memory alive. Doing it by hand means four variables and four cleanup lines that drift apart as the code changes. A disposer collects each cleanup at the moment something is set up, and runs them all with one call.

Write createDisposer() in disposer.js.

Signature

JAVASCRIPT
function createDisposer() // returns a disposer

disposer.add(cleanup)                        // remember a cleanup function
disposer.listen(target, type, handler, options)  // addEventListener now, removeEventListener on dispose
disposer.timeout(fn, ms)                     // setTimeout now, clearTimeout on dispose; returns the id
disposer.interval(fn, ms)                    // setInterval now, clearInterval on dispose; returns the id
disposer.signal                              // an AbortSignal, aborted on dispose
disposer.disposed                            // true once dispose has been called
disposer.dispose()                           // run every cleanup

Requirements

  1. A new disposer is not disposed and its signal is not aborted.
  2. add(cleanup) stores the function; dispose() calls each stored cleanup exactly once, in reverse order of adding. add throws TypeError for a non-function.
  3. A second dispose() does nothing.
  4. After dispose, add(cleanup) runs the cleanup at once, and listen, timeout and interval set nothing up. A cleanup added while dispose is running also runs at once.
  5. listen adds the listener now and removes exactly that listener on dispose, including capture listeners (options may be true or { capture: true, … }). Listeners added elsewhere stay, even one with the same type, handler and capture flag, and so does the same handler given to another disposer. The handler is called as addEventListener would call it: with the event, and with this set to the target (or, for an object with a handleEvent method, that method on the object), even if the function has an own property named call.
  6. timeout and interval work normally until dispose, which cancels them.
  7. dispose() aborts signal, so anything given the signal (listeners added with { signal }, fetch) is released too.
  8. A cleanup that throws does not stop the others. After running all of them (and aborting the signal), dispose throws one AggregateError whose errors lists every failure in the order they happened. The disposer stays disposed.
  9. Each disposer is independent.

Examples

JAVASCRIPT
function openPanel() {
  const disposer = createDisposer();
  disposer.listen(window, "resize", layout);
  disposer.interval(refresh, 30_000);
  disposer.add(store.subscribe(render));   // subscribe returns an unsubscribe function
  fetch("/api/panel", { signal: disposer.signal }).then(fill);
  return () => disposer.dispose();         // one line closes everything
}
JAVASCRIPT
const d = createDisposer();
d.add(() => console.log("first"));
d.add(() => console.log("second"));
d.dispose();   // "second", then "first"
d.dispose();   // nothing
d.add(() => console.log("late"));   // "late", at once

Environment

  • Plain JavaScript in a browser page; the tests call the global createDisposer from disposer.js.
  • Timers run on a virtual clock that replaces setTimeout, setInterval and their clear functions; the tests count waiting timers.
  • Out of scope: async cleanups (returning promises), and removing a single cleanup before dispose.

Hints

  1. Why should the last thing set up be the first thing undone?
  2. removeEventListener(type, handler) sometimes leaves the listener in place. When?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…