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;
});
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;
});
Generators
This gives you complete control over when you want to access the next iteration in the list.
First of all you have to change your code:
Read more about It here
I can advice you to read this answer to find a right solution for sleep
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:... and get the output:
There is no synchronous
wait
orsleep
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 toArray#forEach
: it contains the index of the current element:Using the
index
, we can compute when the function should be executed. But now we have a different problem: theconsole.log('Loop finished.')
is executed before the first iteration of the loop. That's becausesetTimout
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:There is an excellent article about
Promise
s in conjunction withforEach
/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:You need to make use of setTimeout to create a delay and have a recursive implementation
You example should look like
I think recursion offers the simplest solution.
You can use
async/await
,Promise
constructor,setTimeout()
andfor..of
loop to perform tasks in sequence where aduration
can be set set before a task is performed