有没有一种简单的方法可以减慢forEach中的迭代速度(使用普通的javascript)?例如:
var items = document.querySelector('.item');
items.forEach(function(el) {
// do stuff with el and pause before the next el;
});
解决方法:
使用Array#forEach完全可以实现您想要实现的目标 – 尽管您可能会以不同的方式考虑它.你做不到这样的事情:
var array = ['some', 'array', 'containing', 'words'];
array.forEach(function (el) {
console.log(el);
wait(1000); // wait 1000 milliseconds
});
console.log('Loop finished.');
…并获得输出:
some
array // one second later
containing // two seconds later
words // three seconds later
Loop finished. // four seconds later
JavaScript中没有同步等待或休眠功能阻止其后的所有代码.
在JavaScript中延迟某些东西的唯一方法是以非阻塞的方式.这意味着使用setTimeout
或其亲属之一.我们可以使用我们传递给Array#forEach的函数的第二个参数:它包含当前元素的索引:
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.');
使用索引,我们可以计算何时应该执行该函数.但是现在我们有一个不同的问题:console.log(‘Loop finished.’)在循环的第一次迭代之前执行.那是因为setTimout是非阻塞的.
JavaScript在循环中设置超时,但它不等待超时完成.它只是在forEach之后继续执行代码.
为了解决这个问题,我们可以使用Promises.让我们建立一个承诺链:
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.');
});
有一篇关于Promise和forEach / map / filter here的优秀文章.
如果数组可以动态改变,我会变得更加棘手.在这种情况下,我不认为应该使用Array#forEach.试试这个:
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>