Add a delay after executing each iteration with forEach loop
Is there an easy way to slow down the iteration in a forEach (with plain javascript)? For example:
var items = document.querySelector('.item');
items.forEach(function(el) {
// do stuff with el and pause before the next el;
});
What you want to achieve is totally possible with Array#forEach
— although in a different way you might think of it. You can not do a thing like this:
var array = ['some', 'array', 'containing', 'words'];
array.forEach(function (el) {
console.log(el);
wait(1000); // wait 1000 milliseconds
});
console.log('Loop finished.');
... and get the output:
some
array // one second later
containing // two seconds later
words // three seconds later
Loop finished. // four seconds later
There is no synchronous wait
or sleep
function in JavaScript that blocks all code after it.
The only way to delay something in JavaScript is in a non–blocking way. That means using setTimeout
or one of its relatives. We can use the second parameter of the function that we pass to Array#forEach
: it contains the index of the current element:
var array = ['some', 'array', 'containing', 'words'];
var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?
array.forEach(function (el, index) {
setTimeout(function () {
console.log(el);
}, index * interval);
});
console.log('Loop finished.');
Using the index
, we can compute when the function should be executed. But now we have a different problem: the console.log('Loop finished.')
is executed before the first iteration of the loop. That's because setTimout
is non–blocking.
JavaScript sets the timeouts in the loop, but it doesn't wait for the timeouts to complete. It just continues executing the code after the forEach
.
To handle that, we can use Promise
s. Let's build a promise chain:
var array = ['some', 'array', 'containing', 'words'];
var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?
var promise = Promise.resolve();
array.forEach(function (el) {
promise = promise.then(function () {
console.log(el);
return new Promise(function (resolve) {
setTimeout(resolve, interval);
});
});
});
promise.then(function () {
console.log('Loop finished.');
});
There is an excellent article about Promise
s in conjunction with forEach
/map
/filter
here.
I gets trickier if the array can change dynamically. In that case, I don't think Array#forEach
should be used. Try this out instead:
var array = ['some', 'array', 'containing', 'words'];
var interval = 2000; // how much time should the delay between two iterations be (in milliseconds)?
var loop = function () {
return new Promise(function (outerResolve) {
var promise = Promise.resolve();
var i = 0;
var next = function () {
var el = array[i];
// your code here
console.log(el);
if (++i < array.length) {
promise = promise.then(function () {
return new Promise(function (resolve) {
setTimeout(function () {
resolve();
next();
}, interval);
});
});
} else {
setTimeout(outerResolve, interval);
// or just call outerResolve() if you don't want to wait after the last element
}
};
next();
});
};
loop().then(function () {
console.log('Loop finished.');
});
var input = document.querySelector('input');
document.querySelector('button').addEventListener('click', function () {
// add the new item to the array
array.push(input.value);
input.value = '';
});
<input type="text">
<button>Add to array</button>
You need to make use of setTimeout to create a delay and have a recursive implementation
You example should look like
var items = ['a', 'b', 'c']
var i = 0;
(function loopIt(i) {
setTimeout(function(){
// your code handling here
console.log(items[i]);
if(i < items.length - 1) loopIt(i+1)
}, 2000);
})(i)
I think recursion offers the simplest solution.
function slowIterate(arr) {
if (arr.length === 0) {
return;
}
console.log(arr[0]); // <-- replace with your custom code
setTimeout(() => {
slowIterate(arr.slice(1));
}, 1000); // <-- replace with your desired delay (in milliseconds)
}
slowIterate(Array.from(document.querySelector('.item')));
You can use async/await
, Promise
constructor, setTimeout()
and for..of
loop to perform tasks in sequence where a duration
can be set set before a task is performed
(async() => {
const items = [{
prop: "a",
delay: Math.floor(Math.random() * 1001)
}, {
prop: "b",
delay: 2500
}, {
prop: "c",
delay: 1200
}];
const fx = ({prop, delay}) =>
new Promise(resolve => setTimeout(resolve, delay, prop)) // delay
.then(data => console.log(data)) // do stuff
for (let {prop, delay} of items) {
// do stuff with el and pause before the next el;
let curr = await fx({prop, delay});
};
})();
With JS Promises and asnyc/await
syntax, you can make a sleep
function that really works. However, forEach
calls each iteration synchronously, so you get a 1 second delay and then all of the items at once.
const items = ["abc", "def", "ghi", "jkl"];
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
items.forEach(async (item) => {
await sleep(1000);
console.log(item);
});
What we can do instead is use setInterval
and clearInterval
(or setTimeout
but we're using the former) to make a timed forEach loop like so:
function forEachWithDelay(array, callback, delay) {
let i = 0;
let interval = setInterval(() => {
callback(array[i], i, array);
if (++i === array.length) clearInterval(interval);
}, delay);
}
const items = ["abc", "def", "ghi", "jkl"];
forEachWithDelay(items, (item, i) => console.log(`#${i}: ${item}`), 1000);