做这样的事情最好的方法是什么?
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
}
谢谢!
答案 0 :(得分:4)
要每秒处理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();
答案 1 :(得分:3)
我认为这适用于JavaScript:
var b = [1, 2, 3];
var timer;
var i = 0;
function timerFunction() {
// base case
if (i >= b.length) {
clearInterval(timer);
return;
}
var element = b[i];
// do stuff to b here
i++;
}
// if you want to execute it right away
timerFunction();
// start the timer
timer = setInterval(timerFunction, 1000);
答案 2 :(得分:2)
如果你有大量的代码需要每1秒运行一次,你可以使用setInterval
并忘记循环。
setInterval(function() {
// do stuff
}, 1000); // every second (or so... not real time, but close enough)
我相信这可以满足你的要求。好像你想要每秒在循环中运行代码,所以这样就可以了。