Skip to content
Theme:

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.

Comments

  • g
    gregory

    What is the difference between this and removeEventListener

    👆 you can use Markdown here

    Your comment is awaiting moderation. Thanks!
    • Pawel Grzybek
      Pawel Grzybek

      It is going to be easier to explain using a snippet.

      document.addEventListener("mousemove", () => {
        // do some cool things here
      });
      
      document.removeEventListener("mousemove", () => {
        // do some cool things here
      });
      
      // UUuups! There is still handler attached to `mousemove`.
      // Each callback create its own instance and
      // add/remove doesn't work when they are inlined.
      // `AbortController` can help here.
      

      👆 you can use Markdown here

      Your comment is awaiting moderation. Thanks!
  • s
    sunpietro

    This is really nice example, but kind of unintuitive to use.

    👆 you can use Markdown here

    Your comment is awaiting moderation. Thanks!
  • A
    A. Matias Quezada

    Brilliant! had no idea this was possible!

    👆 you can use Markdown here

    Your comment is awaiting moderation. Thanks!

Leave a comment

👆 you can use Markdown here

Your comment is awaiting moderation. Thanks!