0

Once removeEventListener is invoked, is it safe to assume that the removed handler will not be called? This is a somewhat broad question, so here are some specific examples.

  1. A button is clicked, and its click event is dispatched onto the execution queue. Before the event can be handled, removeEventListener is called, removing the button's event handler. What happens?
  2. A function is invoked which takes 3 milliseconds to complete. At the end of this function, removeEventListener is invoked, removing the click handler of a button. During this three-millisecond period, the button is clicked. Will the handler be invoked after the previous function is done executing?

Is it safe to perform cleanup actions in the same function that invokes removeEventListener, or must one use setTimeout or some other method of first ensuring that the execution queue is empty? Does this behavior vary among browsers?

Relevant documentation is also appreciated. Thanks in advance!

0x4e2
  • 1

1 Answers1

0

Just for you to briefly understand how JavaScript runs - it's always thread-safe because it runs only on a single thread.

To answer your first question, if you remove the event listener even after the event is dispatched, the function will be called, because the handler callback function ends up on the call stack. For more information I advise you to read this: javascript/browser: when does event dispatching exactly happen?

To answer your second question, removeEventListener function is synchronous, so that means that there is no possibility to run like this:

removeBrowserListener -> click -> call the event bound function

Because the browser is blocked until it finishes removing the event listener, so no clicks are registered at that time. But even with that, the answer is not that obvious, you should take a look at this question, it tackles the very same problem but from the point of view of binding the event handler, not removing it: Does addEventListener guarantee to be synchronous?

Nhor
  • 3,860
  • 6
  • 28
  • 41
  • I understood that normal Javascript execution all occurred on a single thread, but I wasn't sure whether that also applied to the queuing of DOM events. Thanks for the links, this information is helpful. – 0x4e2 May 28 '17 at 04:08