Javascript: How to put a simple delay in between execution of javascript code?

34.3k views Asked by At

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.

5

There are 5 answers

9
David Tang On BEST ANSWER

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.

0
Darin Dimitrov On

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.

2
T.J. Crowder On

I'd break out the code creating the divs 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

0
Gergely Fehérvári On

it takes much time because the reflows. you should create a document fragment and then adding the brats.

When does reflow happen in a DOM environment?

Javascript Performance - Dom Reflow - Google Article

sleeping will not solve your problem

on the other hand, you creating a string containing the innerhtml and the add to innerhtml. the string stuff really dont needs a big performance, but when you execute the .innerhtml command, it starts a process, which parse your string and creating elements and appending them. you cant interrupt or add a delay.

the innerhtml process cannot be sleeped or interrupted.

you need to generate the elements one by one, and after 50 elemnts added, create a settimeout delay.

var frag = document.createDocumentFragment();

function addelements() {

   var e;
   for(i=0;i<50;++i) {
       e = document.createElement('div');
       frag.appendChild(e);
   }
   dest.appendChild(frag);
   window.setTimeout(addelements,1000);

}
1
Kaushik On

Here is the real trick to put a delay in javascript without hanging the browser. You need to use a ajax function with synchronous method which will call a php page and in that php page you can use the sleep() php function ! http://www.hklabs.org/articles/put-delay-in-javascript