`setInterval` Apparent Infinite Loop

2019-09-05 16:50发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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