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

南楼画角 提交于 2019-12-20 02:42:49

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/48736331/by-using-javascript-recursive-settimeout-function-is-it-risky-to-get-the-stacko

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!