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.
functioncreateDisposer() // returns a disposerdisposer.add(cleanup) // remember a cleanup functiondisposer.listen(target, type, handler, options) // addEventListener now, removeEventListener on disposedisposer.timeout(fn, ms) // setTimeout now, clearTimeout on dispose; returns the iddisposer.interval(fn, ms) // setInterval now, clearInterval on dispose; returns the iddisposer.signal// an AbortSignal, aborted on disposedisposer.disposed// true once dispose has been calleddisposer.dispose() // run every cleanup
A new disposer is not disposed and its signal is not aborted.
add(cleanup) stores the function; dispose() calls each stored cleanup exactly once, in reverse order of adding. add throws TypeError for a non-function.
A second dispose() does nothing.
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.
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.
timeout and interval work normally until dispose, which cancels them.
dispose() aborts signal, so anything given the signal (listeners added with { signal }, fetch) is released too.
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.