Abort Signal for Events


II was going through YouTube when a video by WebDevSimplified caught my attention. It was about using AbortController. Although I have used the AbortController API many times, I had never gone through its documentation.
My understanding was that AbortController could be used to abort an ongoing API call by passing the signal as an option to a web request. As it turns out, AbortController can be used in many ways, and one of them is removing an event listener.
Here’s an example where three event listeners are attached to window
and document
and are removed on unmount using controller.abort()
.
// ....
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
// Attach multiple listeners with inline handlers
window.addEventListener("resize", () => {
console.log("Window resized:", window.innerWidth);
},
{ signal }
);
document.addEventListener("click", (e) => {
console.log("Document clicked at:", e.clientX, e.clientY);
},
{ signal }
);
window.addEventListener("keydown", (e) => {
console.log("Key pressed:", e.key);
},
{ signal }
);
// Cleanup: AbortController will remove all listeners at once
return () => {
controller.abort();
console.log("All event listeners removed");
};
}, []);
// ...
Now there is no need to create a separate function and pass it to the removeEventListener()
method. Here are some resources you can go through to learn more about AbortController:
I also confirmed that this actually removes the the event listener from the window or document by using getEventListeners
method available on Chrome dev tool console.
Add this code to dev tool console to create an AbortController and get the reference to the signal.
const controller = new AbortController(); const { signal } = controller;
Add an click event listener to the document and pass the signal as third argument.
document.addEventListener("click", () => { console.log('Event listener attached', e); }, {signal});
Press enter and check if the event is added to the document.
getEventListerens(document);
Expand the
object
and check underclick
key. You’ll see an array of listeners like thisEvents listereners attached to the 'document'
Now, let’s remove the event listener by aborting the signal using the controller we created in the first step. Run this code:
controller.abort();
Check if listener is removed by running the getEventLister again.
getEventListerens(document);
You’ll either see that the
click
listener is not present in the object, or the listeners array doesn’t have the listener we added for the click event.
That’s it folks!
Subscribe to my newsletter
Read articles from Laxmikant Nirmohi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
