`setInterval` Apparent Infinite Loop

2019-09-05 16:39发布

When I open the HTML with the below JavaScript, starting timer gets logged in the console, but then my mouse icon just spins.

window.onload = function() {
    console.log("starting timer");
    var n = 0;
    var id = setInterval(function() { console.log("hello"); n++ }, 100);
    while(true) {
        if( n > 5 ) {
              clearInterval(id);
              break;
        }
    }
    console.log("finished timer");
}

Am I creating some type of infinite loop here?

3条回答
闹够了就滚
2楼-- · 2019-09-05 17:19

The issue is that the while(true) statement is re-running as fast as possible. As soon as it's done, it starts again, and there is no time left for anything else, freezing up the browser. You should have the setInterval check inside of itself. e.g:

window.onload=function(){
    console.log('starting timer');
    var n=0;
    var id=setInterval(function(){console.log('hello');n++;if(n>5){
        clearInterval(id);
        console.log('finished timer');
    },100);
}
查看更多
狗以群分
3楼-- · 2019-09-05 17:23

JavaScript/DOM is single threaded by design.

And while JS is spinning this loop of yours:

while(true) {
      ...
}

no other JS code gets executed including that callback you provide in setInterval() and so n is always zero.

Therefore, yes, you have infinite loop there.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-09-05 17:26

The issue is that JavaScript is single-threaded. (This is a feature.) Your setInterval function will not execute until that window.onload function returns, which it never will because the break never occurs because n never gets incremented.

查看更多
登录 后发表回答