Last Updated: February 25, 2016
·
18.16K
· rezigned

How to delay javascript loop?

Problem

I came across some problem today, where I would like to delay Javascript loop before it processes next item. How could I do that?

var items = [ 
    [0, 1, 2],
    [3, 4, 5]
];

For example, After it iterates through the first element ([0, 1, 2]) it should wait for X seconds before go to next element ([3, 4, 5])

Solution

We could solve this by using a combination of setTimeout + recursive, here's how I've solved it

function delay_loop(items) {

    var data  = items.shift(),
        // delay between each loop
        delay = 2000;

    // start a delay
    setTimeout(function(){

        // process array data
        for(var i=0, l=data.length; i<l; i++) {
            console.log(data[i]);
        }

        // recursive call 
        if (items.length)
            delay_loop(items)

    }, delay);
}

Try it with delay_loop([[0, 1, 2], [3, 4, 5]]) will yield the following result.

(delay for 2 secs)
1
2
3
(delay for 2 secs)
4
5
6

2 Responses
Add your response

Hello there can you please show me a working example at http://jsfiddle.net/

Please

over 1 year ago ·

I'd much rather use something like async than a timeout ...

over 1 year ago ·