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.
I'd break out the code creating the div
s into a function, and then schedule execution of that function periodically via setTimeout
, like this:
function createThousands(data) {
var index;
index = 0;
doAChunk();
function doAChunk() {
var counter;
for (counter = 50; counter > 0; --counter) {
// Are we done?
if (index >= data.length) {
// Yup
return;
}
// ...create a div...
// Move to the next
++index;
}
// Schedule the next pass
setTimeout(doAChunk, 0); // 0 = defer to the browser but come back ASAP
}
}
This uses a single closure, doAChunk
to do the work. That closure is eligible for garbage collection once its work is done. (More: Closures are not complicated)
Live example