Skip to content Skip to sidebar Skip to footer

`setinterval` Apparent Infinite Loop

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

Solution 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.

Solution 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.

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

Post a Comment for "`setinterval` Apparent Infinite Loop"