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:
addEventListener has a 'once' option, but I mostly want to remove a group of events once one of them fires. Well, soon we'll be able to do that with AbortController!
Details: https://t.co/TaiqShq7MO
— Jake Archibald (@jaffathecake) November 13, 2020
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: