问题
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;
});
回答1:
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>
回答2:
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)
回答3:
First of all you have to change your code:
var items = document.querySelectorAll('.item'), i;
for (i = 0; i < items.length; ++i) {
// items[i] <--- your element
}
You can loop over Arrays easily in JavaScript with forEach, but unfortunately, it's not that simple with the results of a querySelectorAll
Read more about It here
I can advice you to read this answer to find a right solution for sleep
回答4:
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});
};
})();
回答5:
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')));
回答6:
Generators
function* elGenLoop (els) {
let count = 0;
while (count < els.length) {
yield els[count++];
}
}
// This will also work with a NodeList
// Such as `const elList = elGenLoop(document.querySelector('.item'));`
const elList = elGenLoop(['one', 'two', 'three']);
console.log(elList.next().value); // one
console.log(elList.next().value); // two
console.log(elList.next().value); // three
This gives you complete control over when you want to access the next iteration in the list.
来源:https://stackoverflow.com/questions/45498873/add-a-delay-after-executing-each-iteration-with-foreach-loop