I have a for loop which iterates more than 10,000 times in a javascript code. The for loop creates and adds < div > tags into a box in the current page DOM.
for(i = 0; i < data.length; i++)
{
tmpContainer += '<div> '+data[i]+' </div>';
if(i % 50 == 0) { /* some delay function */ }
}
containerObj.innerHTML = tmpContainer;
i want to put a delay after every 50 < div > tags so what will be the code at the place of
/* some delay function */
because its taking too much time to load all 10,000 < div > tags. i want to update the box in chunks of 50 < div > tags.
thanks in advance.
There's a handy trick in these situations: use a setTimeout with 0 milliseconds. This will cause your JavaScript to yield to the browser (so it can perform its rendering, respond to user input and so on), but without forcing it to wait a certain amount of time:
for (i=0;i<data.length;i++) {
tmpContainer += '<div> '+data[i]+' </div>';
if (i % 50 == 0 || i == data.length - 1) {
(function (html) { // Create closure to preserve value of tmpContainer
setTimeout(function () {
// Add to document using html, rather than tmpContainer
}, 0); // 0 milliseconds
})(tmpContainer);
tmpContainer = ""; // "flush" the buffer
}
}
Note: T.J. Crowder correctly mentions below that the above code will create unnecessary functions in each iteration of the loop (one to set up the closure, and another as an argument to setTimeout
). This is unlikely to be an issue, but if you wish, you can check out his alternative which only creates the closure function once.
A word of warning: even though the above code will provide a more pleasant rendering experience, having 10000 tags on a page is not advisable. Every other DOM manipulation will be slower after this because there are many more elements to traverse through, and a much more expensive reflow calculation for any changes to layout.