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
Written by Rezigned
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#