Cancel JavaScript Event Listeners with AbortController

One of the new features that was added in Chrome 88 is the ability to pass an AbortController‘s signal into addEventListener.

const controller = new AbortController();
const { signal } = controller;

document.querySelector('…').addEventListener('foo', (e) => {
  // …
}, {signal});

By calling controller.abort();, you can remove the listener from the event target, just like when calling element.removeEventListener.

💁‍♂️ Did you know you can use the AbortController to abort promises? It was its first intended use case when it was introduced back in 2017.

~

An excellent use-case here is that you can cancel multiple Event Listeners at once using it, as shared by Jake Archibald:

In the example above there are two competing event listeners. Whenever one of them finishes controller.abort(); is called, thus also removing the other one. Cool!

~

🔥 Like what you see? Want to stay in the loop? Here's how:

About the author

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.