Why doesn't triggering click() inside a click event listener cause an infinite loop?

50

Can someone explain the program flow of this JavaScript code:

const $leaveRoom = document.querySelector('#leave-button');
let a = 1;
$leaveRoom.addEventListener('click', () => {
  console.log(a);
  console.log("check");
  a++;
  $leaveRoom.click();
  console.log(a);
  a++;
});
<button id="leave-button">Leave Room</button>
The Output was:
1
check
2
check
3
4

This question may sound dumb but I am new to JavaScript. I am not able to understand the program flow of this code. I want to know how did I get 3 & 4 in the output.

Share
Improve this question
11
  • 1
    you are dealing with a recursive type function. (a function that calls itself) It's not exactly that but sort of. On click 1 and check are output. then the program calls the click function and 2 and check are outputed. then the second part of the first click outputs 3 and finally the second part of the inside call to the click functions outputs 4 – DCR yesterday
  • 1
    @DCR "then the second part of the first click outputs" - but why it doesn't trigger a new click there? Why it exits? – T J yesterday
  • 3
    @DCR - What exactly makes this code not a traditional recursion? – PM 77-1 yesterday
  • 1
    I'm not sure what OP is asking. The most interesting part of this code seems to boil down to "why does calling el.click() inside an element's own event handler not cause an infinite chain of events to fire?" The downvotes are probably because it's not clear what is surprising to OP here, so I'm assuming it's the click call rather than the increment or delayed final console.logs, which could be illustrated without events just as well. – ggorlen yesterday
  • 2
    typical recursion has an end case and a way of reducing the problem on each iteration until you reach the end case – DCR yesterday

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue