javascript – 使用forEach循环执行每次迭代后添加延迟
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 使用forEach循环执行每次迭代后添加延迟,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2944字,纯文字阅读大概需要5分钟。
内容图文
![javascript – 使用forEach循环执行每次迭代后添加延迟](/upload/InfoBanner/zyjiaocheng/708/f9707b8da3a64880af807a083e4ded9d.jpg)
有没有一种简单的方法可以减慢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>
内容总结
以上是互联网集市为您收集整理的javascript – 使用forEach循环执行每次迭代后添加延迟全部内容,希望文章能够帮你解决javascript – 使用forEach循环执行每次迭代后添加延迟所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。