I have this piece of code in javascript which I believe should not lead to stack overflow but it does, because in setInterval, I introduce a statement to stop infinite recursion of another function
let setval = false;
let ctr = 0;
let f = function() {
ctr ;
if (setval == true) {
return;
}
else {
f();
}
}
setTimeout(() => {
setval = true;
}, 1);
f();
why does it behave this way? In 1 ms surely there cannot be 13985 calls to f()
, which is the value of ctr
.
CodePudding user response:
JavaScript execution model is based on event loop. Read more about this model @ below MDN documentation site.