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.
javascript html addeventlistener
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 finalconsole.log
s, which could be illustrated without events just as well. – ggorlen yesterday