Codigo Logo

A typical infinite loop in Javascript

Infinite loop is a cycle that repeats indefinitely because their match condition is never true.

So let's see one example. The appendChildren function should add a new child div to each existing div:

 

function appendChildren() {
var allDivs = document.getElementsByTagName("div");

for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
decorateDiv(newDiv);
allDivs[i].appendChild(newDiv);
}
}

 

This is, after the appendChildren is executed, following divs

<div id="a">
  <div id="b">
  </div>
</div>

should take the following form:

<div id="a">
  <div id="b">
    <div></div>
  </div>
  <div></div>
</div> 

 But instead the script executes an infinite loop. The wrong code here is the variable allDivs. It's dynamic and it's increased in each cycle. So the solution is to define a new variable and save there the initial value of allDivs. With this the infinite loop will be removed.

 

function appendChildren() {
var allDivs = document.getElementsByTagName("div");
var numberOfDivs=allDivs.length;

for (var i = 0; i < numberOfDivs; i++) {
var newDiv = document.createElement("div");
decorateDiv(newDiv);
allDivs[i].appendChild(newDiv);
}
}

 

A typical infinite loop in Javascript