创建循环 SetTimeOut Jquery 数组

Create Loop SetTimeOut Jquery Array

我正在尝试在控制台日志浏览器中创建一个带有 setTimeout 的循环。但它不起作用。我尝试搜索但没有找到我需要的东西。基本上在每个循环中,在此 printa 5sec in late updates 中,间隔为 5sec。必须将数组带入循环。

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

我通常的代码是:

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

不漂亮,但很简单。

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) 的内容。