Skip to content
jshacks.dev
Async

How to Clean Up Event Listeners With AbortSignal

Clean up event listeners with AbortSignal: pass a signal to addEventListener, remove many listeners with one abort and avoid leaks in long-lived pages.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Apache Kafka, Redis and Node.js logos.

Every addEventListener call has a matching removeEventListener that most code forgets. The removal needs the same function reference, the same event name and the same capture flag, so anonymous handlers cannot be removed at all, and a component that adds five listeners must remember five removals. Forgotten listeners keep objects alive, run handlers for elements that are gone and make memory use creep upward. There is a simpler way to clean up event listeners: pass an AbortSignal in the options of addEventListener, and a single abort() removes every listener registered with that signal. This post shows the pattern in browsers and Node.js 24, how it works for several targets, how to tie it to a component's lifetime and the details that decide whether it works. For the signal basics, see implementing a cancelable promise.

The old way and its problems

The classic pairing requires a stable reference to the handler.

manual.jsJavaScript
const target = new EventTarget();

function onPing() {
  console.log("ping");
}

target.addEventListener("ping", onPing);
target.dispatchEvent(new Event("ping"));

target.removeEventListener("ping", onPing);
target.dispatchEvent(new Event("ping")); // nothing happens
Text
ping

This works for one named function. It breaks down when the handler is an arrow function created inline, since there is no reference to pass later, and when the handler is a bound method, since fn.bind(this) creates a new function each time. It also scales badly: ten listeners mean ten removals, and a missed one is a leak that no error reports.

Pass a signal instead

The signal option on addEventListener ties a listener's life to a signal. When the signal aborts, the listener is removed, and it is also removed if the signal was already aborted when you tried to add it.

signal.jsJavaScript
const target = new EventTarget();
const controller = new AbortController();

target.addEventListener("ping", () => console.log("handler A"), { signal: controller.signal });
target.addEventListener("ping", () => console.log("handler B"), { signal: controller.signal });

target.dispatchEvent(new Event("ping"));
controller.abort();
target.dispatchEvent(new Event("ping")); // both are gone
console.log("done");
Text
handler A
handler B
done

Both handlers were anonymous arrow functions, and a single controller.abort() removed both. No references to them were needed. The option is supported by EventTarget in Node.js 15.4 and later, and by all current browsers, and in Node.js the EventEmitter class accepts a signal in events.once and events.on, which cover the common waiting cases.

One signal, many targets

A signal is not tied to one target. Pass the same signal while adding listeners to the window, a document and a few elements, and all of them are removed together. That is the point: the signal represents the lifetime, and everything created during that lifetime attaches to it.

many-targets.jsJavaScript
const controller = new AbortController();
const { signal } = controller;

const a = new EventTarget();
const b = new EventTarget();
const log = [];

a.addEventListener("tick", () => log.push("a"), { signal });
b.addEventListener("tick", () => log.push("b"), { signal });

for (const target of [a, b]) target.dispatchEvent(new Event("tick"));
controller.abort();
for (const target of [a, b]) target.dispatchEvent(new Event("tick"));

console.log(log);
Text
[ 'a', 'b' ]

After the abort, the second round of events reached no handler, so the log has only the first two entries. In a browser you would use window, document and elements here, with the same effect.

Tie it to a component lifetime

A component, a widget or a page section has a start and an end. Create the controller when it starts, pass its signal to every listener, and abort at teardown. That replaces a list of removal calls with one line, and it makes it hard to forget one, since the signal is already in hand when you write the next listener.

widget.jsJavaScript
export class Widget {
  #controller = new AbortController();

  constructor(button, input, log) {
    const { signal } = this.#controller;
    button.addEventListener("click", () => log.push("click"), { signal });
    input.addEventListener("input", () => log.push("input"), { signal });
    document?.addEventListener?.("keydown", () => log.push("key"), { signal });
  }

  destroy() {
    this.#controller.abort();
  }
}

const button = new EventTarget();
const input = new EventTarget();
const log = [];
const widget = new Widget(button, input, log);

button.dispatchEvent(new Event("click"));
widget.destroy();
button.dispatchEvent(new Event("click"));
input.dispatchEvent(new Event("input"));
console.log(log);
Text
[ 'click' ]

After destroy(), neither the click nor the input event reached the log. The optional chaining on document keeps the sample runnable in Node.js, where there is no document, and in a browser the keydown listener joins the same cleanup. Frameworks that give you an effect or lifecycle hook with a cleanup function fit this: create the controller in the effect, and return () => controller.abort().

Combine with once and passive

The signal option sits beside the others in the options object. { once: true, signal } removes the listener after the first call or when the signal aborts, whichever comes first. { passive: true, signal } marks a scroll or touch listener as unable to call preventDefault, which lets the browser scroll without waiting for your code, and still lets one abort remove it.

options.jsJavaScript
const target = new EventTarget();
const controller = new AbortController();
let calls = 0;

target.addEventListener("go", () => calls++, { once: true, signal: controller.signal });

target.dispatchEvent(new Event("go"));
target.dispatchEvent(new Event("go"));
controller.abort();
console.log(calls);
Text
1

The once option removed the listener after the first event, so the second dispatch did nothing, and the later abort had nothing left to remove.

Details that decide whether it works

Add and remove must see the same target and type. The signal removes only listeners that were registered with it. A listener added without the option is not affected by the abort.

The abort is one-way. A signal that has aborted stays aborted, so you cannot reuse it for a second lifetime. Create a new controller each time the component starts.

It does not cancel work already running. Removing a listener stops future events from reaching your handler. A handler that is already running keeps running, and async work it started continues, so pass the same signal to fetch and timers it starts.

Detached targets are fine. If the element is removed from the page and nothing references it, the listeners go with it, and the signal is not needed for memory. It matters most for listeners on long-lived targets such as window, document and shared emitters, which outlive the component.

Spotting leaked listeners

Leaks of this kind are quiet, so look for them on purpose. In Chrome's developer tools, the Memory panel can take heap snapshots before and after opening and closing a component several times. If the number of retained instances grows with each cycle, listeners on a long-lived target are probably keeping them alive. The Event Listeners pane in the Elements panel lists what is attached to a node, and getEventListeners(window) in the console prints the listeners on any target, so you can count them before and after a teardown. In Node.js, emitter.listenerCount("event") does the same job, and the process prints a MaxListenersExceededWarning when a single event collects more than ten listeners, which is often the first visible sign.

A cheap guard in tests is to assert the count. Create the component, check that the target has the expected number of listeners, destroy it and assert that the count is back to zero. That test fails the moment someone adds a listener without the signal.

Using it with async handlers

A handler that starts asynchronous work should carry the same signal into that work. A click handler that calls fetch can pass { signal } to the request, so when the component is destroyed, the pending request is canceled together with the listener. Without that, a response can arrive after teardown and try to update an interface that no longer exists, which is a common source of console errors. The component's single signal then acts as its whole cleanup story: listeners, timers that accept a signal and requests all stop together.

For timers that do not accept a signal, such as the global setTimeout, register a one-time abort listener that clears them: signal.addEventListener("abort", () => clearTimeout(id), { once: true }). That keeps even the timers inside the single abort path.

When the old method is still right

The signal option is not a replacement for everything. When one specific handler must be removed while the others stay, for example removing a one-time hint listener once the user has seen the hint, a named function and removeEventListener is clear and direct. When you need to remove a listener from code that does not own the controller, the same applies. Use the signal for groups tied to a lifetime, and the manual form for individual cases, and do not mix both on the same listener, since the result is hard to reason about.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.