Sub topic 15
Using a Signal to Remove Event Listeners
This chapter assumes you know addEventListener and removeEventListener, closures, and the AbortController basics from earlier chapters. The examples use the standard EventTarget class. It exists in browsers and in Node.js 15 and later, so you can run every snippet in Node without a DOM.
Until now, the signal has cancelled work that finishes: a delay, a fetch, a loop. Some functions never finish on their own. They set up a subscription, such as a click handler, a resize watcher, or a message listener, and that subscription lasts until someone tears it down. The signal option of addEventListener lets an AbortSignal do that teardown. It uses the same cancellation model as everything else in this tutorial.
The signal option of addEventListener
The third argument of addEventListener can be an options object, and one of its fields is signal. When that signal aborts, the platform removes the listener for you.
const target = new EventTarget();
const controller = new AbortController();
target.addEventListener('ping', () => {
console.log('ping received');
}, { signal: controller.signal });
target.dispatchEvent(new Event('ping')); // "ping received"
controller.abort();
target.dispatchEvent(new Event('ping')); // nothing: the listener is goneYou never kept a reference to the arrow function, and you never called removeEventListener. The usual reason for naming a handler is so you can pass the same reference to removeEventListener later. With a signal you don't need that reference.
One signal, many listeners
The pattern pays off once a function registers several listeners, possibly on different targets. All of them can share one signal, so a single abort() removes them all.
const network = new EventTarget();
const settings = new EventTarget();
const controller = new AbortController();
const { signal } = controller;
network.addEventListener('online', () => console.log('online'), { signal });
network.addEventListener('offline', () => console.log('offline'), { signal });
settings.addEventListener('change', () => console.log('settings changed'), { signal });
network.dispatchEvent(new Event('online')); // "online"
settings.dispatchEvent(new Event('change')); // "settings changed"
controller.abort();
network.dispatchEvent(new Event('offline')); // nothing
settings.dispatchEvent(new Event('change')); // nothingThe alternative is to keep three handler references and make three removeEventListener calls with matching arguments. That bookkeeping is easy to get wrong, especially with the capture flag. A listener added with capture: true must be removed with capture: true, or the removal silently does nothing. The signal removes the exact registration it was attached to, so this mismatch can't happen.
Writing subscription functions that accept a signal
This is the same API convention you used for promise-returning functions: an optional signal in the options object. The function forwards the signal to every listener it adds and ties any other resources, such as timers, to the signal's abort event.
function watchConnection(target, { signal, onStatus } = {}) {
signal?.throwIfAborted();
target.addEventListener('online', () => onStatus('online'), { signal });
target.addEventListener('offline', () => onStatus('offline'), { signal });
const heartbeatId = setInterval(() => onStatus('heartbeat'), 1000);
signal?.addEventListener('abort', () => {
clearInterval(heartbeatId);
}, { once: true });
}
const network = new EventTarget();
const controller = new AbortController();
watchConnection(network, {
signal: controller.signal,
onStatus: (status) => console.log(status),
});
network.dispatchEvent(new Event('offline')); // "offline"
setTimeout(() => {
controller.abort(); // removes both listeners and stops the heartbeat
network.dispatchEvent(new Event('online')); // nothing
}, 2500); // logs "heartbeat" twice before this runsThe listeners clean themselves up through the signal option. The interval is not an event listener, so the function registers its own abort handler to clear it. This is the cleanup discipline from the "Cleaning Up After Abort and After Success" chapter, applied to a function that has no success case.
The throwIfAborted() call at the top matters here. Without it, an already-aborted signal would leave you with no listeners (see the next section) but a running interval. The abort event has already fired and won't fire again, so that interval would never be cleared.
Edge cases and gotchas
An already-aborted signal adds nothing
If the signal is already aborted when you call addEventListener, the listener is never added. No error is thrown.
const target = new EventTarget();
const signal = AbortSignal.abort();
target.addEventListener('ping', () => console.log('never runs'), { signal });
target.dispatchEvent(new Event('ping')); // nothingThis is usually what you want, but it can hide bugs. If listeners mysteriously never fire, check whether you are reusing a controller that was aborted earlier. Once aborted, a controller can't be reset. Create a new one for each new lifetime.
Duplicate registrations are ignored, signal and all
addEventListener deduplicates on the type, the callback, and the capture flag. If you add the same function twice with different signals, the second call is a no-op, and its signal has no effect.
const target = new EventTarget();
const first = new AbortController();
const second = new AbortController();
function handler() {
console.log('handled');
}
target.addEventListener('x', handler, { signal: first.signal });
target.addEventListener('x', handler, { signal: second.signal }); // ignored
second.abort();
target.dispatchEvent(new Event('x')); // "handled": still registered
first.abort();
target.dispatchEvent(new Event('x')); // nothingInline arrow functions avoid this problem because each one is a new function. Shared, named handlers are where it shows up.
Mixing signal removal and manual removal
The two removal methods work together. You can still call removeEventListener on a listener that was added with a signal, and a later abort then has nothing left to remove. The reverse doesn't work: aborting a signal never removes listeners that were added without it.
Removal during dispatch
If one listener aborts the controller while an event is being dispatched, any listeners removed by that abort are skipped for the rest of that dispatch. They don't get a final call.
Scope your signals
Every registration with a signal adds a small internal step to that signal. Don't attach an unbounded number of short-lived listeners to one signal that lives for the whole app and never aborts. Give each subscription, component, or request a controller with a matching lifetime. Then combine signals when a listener should end with whichever scope ends first.
Combining with timeouts and other signals
Any AbortSignal works in the signal option, including the ones from AbortSignal.timeout() and AbortSignal.any().
const target = new EventTarget();
const pageController = new AbortController();
// Listen for at most 3 seconds, or until the page scope ends, whichever is first.
const signal = AbortSignal.any([
pageController.signal,
AbortSignal.timeout(3000),
]);
target.addEventListener('message', () => console.log('message'), { signal });
target.dispatchEvent(new Event('message')); // "message"
setTimeout(() => {
target.dispatchEvent(new Event('message')); // nothing: timed out
}, 3500);Choosing between the approaches
| Approach | Needs a handler reference | Removes many at once | Works with timeouts and `any()` | Typical use |
|---|---|---|---|---|
| `removeEventListener` | Yes, plus matching `capture` | No | No | One listener with simple local scope |
| `{ once: true }` | No | No | No | Listener that should fire a single time |
| `{ signal }` | No | Yes | Yes | Subscriptions tied to a component, request, or caller lifetime |
The options combine. { once: true, signal } removes the listener after the first event or on abort, whichever comes first.
Exercise
A function calls target.addEventListener('tick', onTick, { signal }) and also starts setInterval. A caller passes AbortSignal.abort(), a signal that is already aborted, and the function has no throwIfAborted() check. What happens to the listener and to the interval?
Show answer
The listener is never added, because an already-aborted signal makes addEventListener a no-op. The interval still starts. The signal's abort event fired before the function ran and won't fire again, so the abort handler that would clear the interval never runs and the interval leaks. Calling signal?.throwIfAborted() at the start of the function, before any setup, prevents this.
Exercise
You register the same named function handler on one target for the 'resize' event twice: first with signal A, then with signal B. You abort B. Does handler still run on the next 'resize' event? Why?
Show answer
Yes. The second addEventListener call has the same type, callback, and capture flag as the first, so it is ignored as a duplicate, and signal B is never attached. Only aborting A removes the listener. To give each registration its own lifetime, use separate function instances, for example inline arrow functions.
Exercise
Rewrite button.addEventListener('click', onClick) so the listener is removed either when controller aborts or after 10 seconds, whichever comes first.
Show answer
button.addEventListener('click', onClick, { signal: AbortSignal.any([controller.signal, AbortSignal.timeout(10000)]) });