R01010010 R01010010 - 10 months ago 46
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.

<div id="body"></div>
for(var i = 0; i < 1000000; i++){

Answer Source

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
    setTimeout(loop.bind(null, i+1), 0);