The following code segment demonstrates a recursive call using JavaScript.
function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}
The source is from here.
My question: Doesn’t this lead to a stack build-up and subsequently a stack overflow? I know for a fact that this will certainly crash in languages like Pascal and C/C++.
Thanks for any advice on this.
That’s not real recursion and thus does not create a deep call stack.
However, you should never pass a string to
setInterval()orsetTimeout(). Doing so is as bad as usingeval()and it results in potentially unreadable and possibly insecure code as soon as you use variables since you need to insert them into the string instead of passing the actual variable.The proper solution is
setTimeout(function() { /* your code *) }, msecs);. The same applies tosetInterval(). If you just want to call a single function without any arguments, you can also pass the function name directly:setTimeout(someFunction, msecs);(note that there are no()behind the function name)So in your case, use
t = setTimeout(timedCount, 1000);