Back to topics

Removing Event Listeners with AbortController

Just a note about what I learned today: removing event listeners with AbortController.

Classic Approach

EventTarget.removeEventListener()

Pass the reference of the callback function that was used when binding the event to removeEventListener, and the event listener will be removed.

This is probably the most common approach. In my opinion, it has two disadvantages:

  1. Removing multiple events at once is cumbersome; for example, to remove 5 events, you need to call removeEventListener 5 times.

  2. When using addEventListener, you cannot comfortably use arrow functions, because to maintain a reference to the function, you usually need to define a separate callback function.

Method Based on AbortController

Notice the signal property of the third parameter options object of addEventListener; this property accepts an AbortSignal. When the AbortSignal.abort() method is called, the listener will be removed.

const controller = new AbortController();

window.addEventListener('resize', listener, { signal: controller.signal });

controller.abort();

Common Usage of AbortController

Here's a typical example of aborting a request:

const controller = new AbortController();
const signal = controller.signal;

downloadBtn.addEventListener("click", fetchVideo);

abortBtn.addEventListener("click", () => {
  controller.abort();
  console.log("Download aborted");
});