-3

I stumbled on this piece of code while reading about JavaScript events, and I don't understand why the callback function for removeEventListener doesn't lead to the function being called over and over again. Here's the code:

const button = document.querySelector('button');
function once() {
  alert('Done');
  button.removeEventListener('click', once);
}
button.addEventListener('click', once);

When is clicked, the function onceis called, alerting and then calling removeEventListener - but then removeEventListener calls once, so in my mind this should result in alerts being fired indefinitely. When I load the page however, it works out. Why so?

  • 3
    Do you know what it does? It deletes the element listener from the element. It is not calling it.... Read the docs https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener – epascarello Aug 24 '23 at 19:20
  • 1
    Why would it? Adding or removing a callback function doesn't call it yet. – derpirscher Aug 24 '23 at 19:22
  • 2
    "*but then `removeEventListener` calls `once`*" - no it doesn't?! And there's no `once()` call in your code either. – Bergi Aug 24 '23 at 19:22
  • 1
    `once` references the function *(as opposed to calling it)*, `once()` calls it. See [this question](https://stackoverflow.com/q/7969088/438992) for example if that's not making sense. – Dave Newton Aug 24 '23 at 19:24

0 Answers0