Monday, May 20, 2024
98
rated 0 times [  100] [ 2]  / answers: 1 / hits: 34323  / 14 Years ago, sun, february 6, 2011, 12:00:00

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.


More From » javascript-framework

 Answers
331

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.


[#93873] Friday, February 4, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristinsonjab

Total Points: 364
Total Questions: 98
Total Answers: 98

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
kristinsonjab questions
Fri, Mar 4, 22, 00:00, 2 Years ago
Fri, Jan 22, 21, 00:00, 3 Years ago
Fri, Aug 14, 20, 00:00, 4 Years ago
;