R01010010 R01010010 - 1 month ago 5
HTML Question

Add one element to the DOM at every iteration not all at the end of the loop

I'm not a pure front end developer and I wonder why, in a loop where at every iteration an element is added to the DOM, the resulting DOM is only visible at the end of the loop and not progressively.

<html>
<body>
<div id="body"></div>
</body>
<script>
for(var i = 0; i < 1000000; i++){
document.getElementById('body').appendChild(document.createElement('br'));
document.getElementById('body').appendChild(document.createTextNode(i));
}
</script>
</html>

Answer

Javascript runs code to completion before the repaint events get processed. So in order to get the display updated at regular times, you need to end the script execution at regular times and put something in the event queue that will call back your function for proceeding further.

For instance, you can do this will setTimeout:

(function loop(i) {
    if (i > 100) return; // end condition
    document.body.appendChild(document.createElement('br'));
    document.body.appendChild(document.createTextNode(i));
    setTimeout(loop.bind(null, i+1), 0);
})(0);