Can a stack overflow be avoided in javascript by using the setTimeout method to call a function instead of calling it directly? My understanding of setTimeout is that it should start a new callstack. When i look in the callstack of both chrome and IE it seems that the setTimeout calls are waiting for the function call to return.
Is this just a property of the debugger or is my understanding flawed?
EDIT
While the answers provided below are correct, the actual problem I was having was related to the fact that I was calling setTimeout(aFunction(), 10) which was evaluating aFunction immediately because of the brackets. This question sorted me out.
If you call setTimeout() with a time of 0 ms, the function you specify is not invoked right away. Instead, it is placed on a queue to be invoked “as soon as possible” after any currently pending event handlers finish running.
Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute.
setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.
No, setTimeout does not pause execution of other code.
I can confirm that the stack is cleared.
Consider this scenario:
function a() {
b();
}
function b() {
c();
}
function c() {
debugger;
setTimeout( d, 1000 );
}
function d() {
debugger;
}
a();
So there are two breakpoints - one at the beginning of function c
, and one at the beginning of function d
.
Stack at first breakpoint:
Stack at second breakpoint:
Live demo: http://jsfiddle.net/nbf4n/1/
Async invocations, such as those from setTimeout
, do indeed generate a new callstack.
It's not entirely clear what you're describing when you say "When i look in the callstack of both chrome and IE it seems that the setTimeout calls are waiting for the function call to return." But, one thing you can do is put a breakpoint inside of a function called by setTimeout
, and see that the callstack is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With