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!

~

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. 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 …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

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.