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.
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/