我正在尝试在控制台日志浏览器中使用setTimeout创建一个循环。但它没有用。我试过搜索但没找到我需要的东西。基本上在每个循环中,在此更新期间的5秒内,该循环将是5秒。必须将一个数组带入循环。
var myArray1 = new Array( "orange", "blue", "white" );
for (var i = 0; i <= myArray1.length; i++) {
console.log("This fruit" + myArray1[i] + "is delcious!");
setTimeout(function(){ alert() }, 500); //AFTER FIVE SECONDS
setTimeout(function(){
} //CLOSE FOR
}, 5000); //AFTER FIVE SECONDS
让我举一个我用过的例子并且它有效,但是代码太大了。我想要一种更好地理解循环的方法。
var myArray1 = new Array( "orange", "blue", "white" );
var var_time = 7000;
setTimeout(function(){
console.log("Fruit is " + myArray1[0]);
console.log("...stage 1 loading");
setTimeout(function(){
console.log("Fruit is " + myArray1[1]);
console.log( "...stage 2 loading");
setTimeout(function(){
console.log("Fruit is " + myArray1[2]);
console.log( "stage 2 finish");
alert();
console.log( "You code run perfect");
}, var_time); //stage 2
}, var_time); //stage 1
}, 500); //stage 0
答案 0 :(得分:1)
不漂亮,但很简单。
var fruitColors = ["orange", "blue", "white"];
function showColor(index) {
if (index < fruitColors.length) {
console.log("Fruit is " + fruitColors[index]);
setTimeout(function() { showColor(index+1); }, 500);
}
}
setTimeout(function() { showColor(0); }, 500);
更漂亮但更复杂的方式是:
var fruitColors = ["orange", "blue", "white"];
fruitColors.reverse().reduce(function(m,c) {
return function() {
console.log("Fruit is " + c);
setTimeout(m, 500);
};
}, function() {})();
您可以阅读reduce here (MDN)。
答案 1 :(得分:0)
我通常的代码是:
var myArray1 = [ "orange", "blue", "white" ];
(function loop() {
// find first element and do something with it
var current = myArray1.shift();
...
if (myArray1.length) {
setTimeout(loop, 5000);
}
})(); // start immediately
这当然会在循环运行时改变数组 - 如果这是一个问题,请复制一份。
更通用的版本是:
function repeat(array, delay, callback, done) {
var a = array.slice();
(function loop() {
var x = a.shift();
callback(x);
if (a.length) {
setTimeout(loop, delay);
} else {
done();
}
})();
};
用法:
repeat(myArray1, 5000, function(f) {
console.log(f)
}, function() {
console.log(done);
}