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.