JavaScript createElement: for the loop to hang; while the loop is not working. What for?

This is a question of pure curiosity, as it puzzles me. I'm on Ubuntu 12.04 and I tried this on Firefox 19.0.2 and Chromium 25.0.1364.160. Look at the following two snippets of JavaScript code (these are excerpts from most of the code):

var Div = document.createElement('div');
var limit = 5;

var i = 0;
while (i<limit){
    var img = document.createElement('img');
    img.setAttribute('src', anImage);
    Div.appendChild(img);
    i++;
}
return Div;

and

var Div = document.createElement('div');
var limit = 5;

for (i=0; i<limit; i++){
    var img = document.createElement('img');
    img.setAttribute('src', anImage);
    Div.appendChild(img);
}
return Div;

Now the while loop works as expected, while the for for loop freezes the browser. Why is this so? Where is the difference?

I was looking for a similar case on Interwebs, but nothing went in cycles like the perfect answer. Here are similar, but not quite the same.

Adding Elements to the DOM in a Loop Structure

For Loop Freezes Javascript?

Actually, the second gave me the idea to try the while loop, but it never explains why this matters ...

Thanks for any clarification :)

+5

All Articles