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.
To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.
To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.
Conclusion. setTimeout() is a method that will execute a piece of code after the timer has finished running. let timeoutID = setTimeout(function, delay in milliseconds, argument1, argument2,...); The delay is set in milliseconds and 1,000 milliseconds equals 1 second.
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.
You could use the window.setTimeout function to delay the execution of some code:
if(i % 50 == 0) {
window.setTimeout(function() {
// this will execute 1 second later
}, 1000);
}
But your javascript will continue to execute. It won't stop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With