I have a javascript function that loads 100 div’s from a xmlhttprequest function. I would like it so that the browser shows them loading one by one, and so the user can see the progress. However with the function below I see nothing until everything is loaded. How can I get the browser to ‘redraw’ the page after each child div is attached?
window.onLoad = function ()
{
var i;
for (i=1;i<=100;i++)
{
var newdiv = document.createElement('div');
newdiv.innerHTML = httpget('getitem.pl?component=' + i);
var maindiv = document.getElementById('maindiv');
maindiv.appendChild(newdiv);
document.getElementById('progressdiv').innerHTML = 'Progress: ' + i + ' of 100';
}
document.getElementById('progressdiv').innerHTML = 'Loaded.';
}
You can’t do it within a function. You need to let the browser breathe, normally using
setTimeout(fn, 0).Javascript and browser’s UI are running in the same thread; as long as you keep executing JS, the UI will not update.
setTimeoutwill push a new “job” on the queue, and then theloopfunction will exit. This ends the current “job”. Next in the queue will be any changes in the UI; when that is done, the nextloop“job” will commence.