I’ve made a dead simple loop to demonstrate my question:
var listMaker = function() {
document.getElementById('list').innerHTML = "";
var i = 1;
while (i < 150) {
document.getElementById('list').innerHTML += "<li>" + i + "</li>";
i++;
}
};
I would think that this function would immediately begin to print off to a list, adding each number one at a time.
Instead, it waits until it finished and then pushed the complete list of 150 numbers.
http://jsfiddle.net/mholubowski/CFQ8K/1/ <- working example, check it out!
Why?
The browser runs JS and does page updates on the same thread. This means it will not update the display while your function is running. So in a sense the items are added one at a time, but you can’t see them until the display is repainted after they are all added.
From the user’s point of view the browser will be locked up until the JS finishes, so a long-running loop is a bad idea.
You can rewrite your loop using
setTimeout()and then you can see them appear on the page one at a time.Demo: http://jsfiddle.net/CFQ8K/2/
The
setTimeout()function queues up execution of a function for later, allowing the current function to complete, in turn allowing the browser to repaint the screen.The second parameter of
setTimeout()is the delay in milliseconds – obviously you’d set that as appropriate depending on the effect you are after.