javascript - 在使用 forEach 循环执行每次迭代后添加延迟

标签 javascript loops foreach delay pause

是否有一种简单的方法来减慢 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 中没有同步的 waitsleep 函数会阻塞其后的所有代码。

在 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 之后的代码。

为了处理这个问题,我们可以使用 Promise。让我们构建一个 promise 链:

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.');
});

有一篇关于 PromiseforEach/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>

关于javascript - 在使用 forEach 循环执行每次迭代后添加延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45498873/

相关文章:

java - 作为二项式的递归函数到迭代函数

java8 + foreach循环的内部工作

powershell - 如何在 PowerShell 中退出 ForEach-Object

javascript - 这是确定 JavaScript 变量类型的有效方法吗?

javascript - jquery addClass 和 removeClass 没有按预期工作

javascript - 在列表文本装饰中的悬停文本上不起作用

javascript - 将数据添加到 DataTables 表时无法更改页面

javascript - js中的双向循环

r - 累积循环包括向量中的最后一个变量

javascript - 如何检查数组中是否存在值并且值的计数大于 1?