Skip to content Skip to sidebar Skip to footer

Javascript: How To Put A Simple Delay In Between Execution Of Javascript Code?

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 <

Solution 1:

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 tmpContainersetTimeout(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.

Solution 2:

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.

Solution 3:

I'd break out the code creating the divs into a function, and then schedule execution of that function periodically via setTimeout, like this:

functioncreateThousands(data) {
    var index;

    index = 0;
    doAChunk();

    functiondoAChunk() {
        var counter;

        for (counter = 50; counter > 0; --counter) {
            // Are we done?if (index >= data.length) {
                // Yupreturn;
            }

            // ...create a div...// Move to the next
            ++index;
        }

        // Schedule the next passsetTimeout(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

Solution 4:

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();

functionaddelements() {

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

}

Solution 5:

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

Post a Comment for "Javascript: How To Put A Simple Delay In Between Execution Of Javascript Code?"