gpt4 book ai didi

javascript - 你会如何在定时器上做一个 for 循环?

转载 作者:行者123 更新时间:2023-12-03 19:01:07 25 4
gpt4 key购买 nike

做这样的事情最好的方法是什么?

for a in b
#do this thing
#wait a second, then continue the loop

在 js 中

var a, _i, _len;

for (_i = 0, _len = b.length; _i < _len; _i++) {
a = b[_i];
//do this thing
//wait a second, then continue the loop
}

谢谢!

最佳答案

要每秒处理 for (i in b) 循环中的一个项目,直到您完成这些项目,您可以这样做:

var list = [];
// accumulate list of items to operate on into an array
// that can be incremented through
for (var i in b) {
list.push(i);
}

function next() {
if (list.length > 0) {
var item = list.shift();
// do something with the next item here

// do the next iteration one second later
setTimeout(next, 1000);
}
}
// start it
next();

关于javascript - 你会如何在定时器上做一个 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9526706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com