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 中没有同步的 wait 或 sleep 函数会阻止其后的所有代码。
在 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.');
使用index,我们可以计算何时应该执行该函数。但是现在我们有一个不同的问题: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.');
});
有一篇关于Promises 和forEach/map/filterhere 的优秀文章。
如果数组可以动态更改,我会变得更棘手。在那种情况下,我认为不应该使用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>