Search code examples
javascriptrecursionsettimeoutstack-overflow

By using javascript recursive setTimeout function, is it risky to get the stackoverflow?


By using javascript recursive setTimeout function, is it risky to get the stackoverflow?

By trying this example you can see in browser console that the stack grows. Why is it so?

var iteration = 0;
  function bar() {
    iteration++;
    console.log("iteration: " + iteration);
    console.trace();
    if(iteration < 5){
    	setTimeout(bar, 5000);
    } 
  }

bar();


Solution

  • By using javascript recursive setTimeout function, is it risky to get the stackoverflow?

    No. setTimeout registers a handler that will get called by the browser when the timer triggers. By the time that happens, the stack has unwound (if it hadn't, the task that scheduled the timeout wouldn't have ended, and the browser's UI would be locked up waiting for it to end).

    By trying this example you can see in browser console that the stack grows.

    No, the stack unwinds before the handler is next called. If you're referring to the async "stack" entries that Chrome's devtools show you, those aren't the real stack, and they're a devtools artifact. (Start your timer, watch for two ticks so you see the "async" entry on the second one, then close your console, wait two more ticks, and reopen it; notice that there aren't any "async" entries — at all, not even the one you saw it log before closing the console!)