8

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();

2
  • 3
    "By trying this example you can see in browser console that the stack grows." What makes you think that? Commented Feb 11, 2018 at 20:55
  • are you perhaps running in an environment where setTimeout has been mocked with a synchronous version? Commented Feb 11, 2018 at 20:57

1 Answer 1

12

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!)

Sign up to request clarification or add additional context in comments.

1 Comment

Now, if the question had been "what are these (async) stack entries I'm seeing" it wouldn't be a duplicate, but the question actually asked is indeed a dupe... :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.