0

With timeouts, I can do something like

let x = setTimeout(func, 0);
clearTimeout(x);

Is there a way to do something like

let x = document.addEventListener("click", func);
clearEventListener(x);

I can't seem to ever find a straightforward way of doing this and it comes up quite often.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Dara Java
  • 2,410
  • 3
  • 27
  • 52
  • 3
    `document.removeEventListener('click', func);` ?? – CertainPerformance Jun 13 '18 at 00:50
  • 1
    You might want to Google for the "removeEventListener" method, built in to remove event listeners. – Félix Adriyel Gagnon-Grenier Jun 13 '18 at 00:50
  • 1
    No, because if I add the same function twice, and call removeEventListener, then it removes both of them. That doesn't happen when I use clearTimeout – Dara Java Jun 13 '18 at 00:54
  • 1
    can you add the same function twice? I tried 2 `.addEventListener("click", f)`, and it's called only once .. – Slai Jun 13 '18 at 01:02
  • 1
    *"No, because if I add the same function twice,"* Why are you adding the same function twice? That makes no sense. Also @Slai is right, you cannot add the same handler twice: *"If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener() method."* https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Other_notes – Felix Kling Jun 13 '18 at 01:04
  • 1
    Unless you provide more information and a better example of your situation, this is a duplicate of https://stackoverflow.com/q/15100576/218196 – Felix Kling Jun 13 '18 at 01:09

1 Answers1

2

Below is example code that adds an event listener to an element and then removes it the first time the event is handled. You can confirm that the event listener is removed by clicking the button a second time and observing that the handler function isn't executed.

var eventHandler = function(e) {
  console.log('Handled the event once - now I\'m going to remove the eventListner via removeEventListener.');
  //remove the event handler
  e.target.removeEventListener('click', eventHandler);
}

//add an event handler
document.getElementById('btn').addEventListener('click', eventHandler);
<input id="btn" type="button" value="Example">

Here is the mdn documentation for those methods:

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener

Tom O.
  • 5,730
  • 2
  • 21
  • 35