Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does calling setTimeout clear the callstack?

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.

like image 241
Aran Mulholland Avatar asked Nov 08 '11 23:11

Aran Mulholland


People also ask

What happens when if setTimeout () call with 0ms?

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.

Does setTimeout block the main thread?

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.

What is the effect of setTimeout?

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.

Does setTimeout stop execution?

No, setTimeout does not pause execution of other code.


2 Answers

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:

  • c()
  • b()
  • a()

Stack at second breakpoint:

  • d()

Live demo: http://jsfiddle.net/nbf4n/1/

like image 79
Šime Vidas Avatar answered Oct 12 '22 05:10

Šime Vidas


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.

like image 37
Domenic Avatar answered Oct 12 '22 03:10

Domenic