TIL — Removing DOM Event Handlers using AbortController
Thanks to Dan, who recommended “AbortController is your friend” by Sam Thorogood, today I learned about the ability to remove DOM event handlers using AbortController. Sam’s article is full of good use cases for this controller, but this one blew my mind.
const controller = new AbortController();
document.addEventListener(
"mousemove",
() => {
// do some cool things here
},
{ signal: controller.signal }
);
// later on
controller.abort();
Look at this example that tracks a mousemove event on the document, prints the coordinates and can be aborted on demand by clicking a button. So nice!
See the Pen 2022-06-18 by Pawel Grzybek (@pawelgrzybek) on CodePen.
Baseline: AbortController and AbortSignal is widely available
- Google Chrome
66 2018.04.17
- Microsoft Edge
16 2017.10.17
- Firefox
57 2017.11.14
- Safari
12.1 2019.03.25
What is the difference between this and removeEventListener
It is going to be easier to explain using a snippet.
This is really nice example, but kind of unintuitive to use.
Brilliant! had no idea this was possible!