You probably know that you can remove an event listener using the .removeEventListener()
method:
const button = document.querySelector('button');
function handleClick(event) {
// ...
}
// Add the event listener
button.addEventListener('click', handleClick);
// Remove the event listener
button.removeEventListener('click', handleClick);
AbortController and AbortSignal
But did you know you can do it using an AbortSignal
?
const button = document.querySelector('button');
// Create a new AbortController object instance
const controller = new AbortController();
// Create a reference to its associated AbortSignal object
const { signal } = controller;
function handleClick(event) {
// ...
}
// Add the event listener
// Associate it with the signal and controller
button.addEventListener('click', handleClick, { signal });
// Remove the event listener
controller.abort();
We create a new AbortController
object instance. Then we use destructuring assignment to create a reference to its associated AbortSignal
object:
const controller = new AbortController();
const { signal } = controller;
The .addEventListener()
method accepts an optional object of options as its third argument. When we add the event listener, we use the object property shorthand to set the value of the signal
property to the value of the signal
constant. This is the AbortSignal
object we created a reference to:
button.addEventListener('click', handleClick, { signal });
When we're ready to remove the event listener, we call the .abort()
method of the AbortController
object instance:
controller.abort();
Benefits
This may seem more verbose, but it has a couple of benefits:
- You can remove multiple event listeners at once. Just associate them all with the same
AbortSignal
. - You can remove anonymous event listeners. The
.removeEventListener()
method only works with named functions.
Browser support
The AbortController
interface has been around for a little while (Chrome 66, Edge 16, Firefox 57, and Safari 12.1). However, the options.signal
property is very new to the .addEventListener()
method. It only became available in the following browser versions:
- Chrome 90
- Edge 90
- Firefox 86
- Opera 76
It is not currently supported in Safari, Opera for Android, or Safari for iOS. You can follow the support status on Can I Use.
There is a polyfill you can use to improve browser support.