A JavaScript infinite loop is one of the most dreaded errors when coding in JavaScript because the code inside the loop will just run forever. This can be dangerous if there is a lot of code inside the loop, as it will use a ton of your browser’s resources and usually cause a crash.

Here are two examples of an infinite loop in JavaScript. One in a for loop and one in a while loop.

for( var i = 1; i > 0; i++  ){
  //The code inside this for loop will never stop
}
var i = 1;
while( i > 0 ){
  //The code inside this while loop will never stop
  i++;
}

In the for loop above, the code will generate an infinite loop because the variable i is set to the number 1 to start. You then have the natural progression of a for loop in that you keep increasing the value of the number until it reaches a condition that will not be true, that will stop the loop. However, in the code above, that condition is that i > 0. Since i (which is 1) is greater than 0, we add 1 to it and try again. We get 2 > 0, which is also true. We then repeat the step until, well forever. Because we are adding 1 each time, the condition i > 0 will always be true, and so the loop will run forever.

The second example is basically the same as the for loop. The while condition of i > 0 will always be true and so the code inside the while loop will run forever.

Let’s take a look at one of these in action.

JavaScript Infinite Loop in Action, Kind Of

In this example, we will run an infinite loop, well kind of. Because we don’t want to crash your browser, we will show the start of an infinite loop, and add some safety code to make sure you always avoid infinite loops.

In our HTML we will just have a simple button that will start the loop. The setup is pretty simple.

Start Loop

The javascript for this example will be pretty simple. We will run the while infinite loop example from above with some code in it. We will show what value i has to the user using the textContent property.

Like we said at the start, since we don’t want to do any damage, we will put a safety check in place. We will not let this code run more than 1000 times. We can set this number to some number we know should not be reached if the code runs correctly. So we will add some code into the while loop and add a conditional check to make sure we avoid the infinite loop.

Here is the JavaScript code:

var i = 1;
var infiniteLoopSafetyCheck = 0;
function startLoop(){
  while( i > 0 && infiniteLoopSafetyCheck < 1000 ){
    document.getElementById("loop-text").textContent = document.getElementById("loop-text").textContent + i;
    i++;
    infiniteLoopSafetyCheck++;
  }
}

The final code and output for this example of a JavaScript infinite loop is below:

Code Output:

Start Loop

Full Code:

Start Loop

Hopefully this article has been useful for you to understand the JavaScript infinite loop.

Categorized in:

JavaScript,

Last Update: March 13, 2024