创建循环设置超时 jquery 数组

Create Loop SetTimeOut Jquery Array

本文关键字:jquery 数组 超时 设置 循环 创建      更新时间:2023-09-26

我正在尝试在控制台日志浏览器中创建一个带有setTimeout的循环。但它不起作用。我尝试搜索,但没有找到我需要的东西。基本上在每个循环中,在后期更新中,此打印期间的间隔为 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

不漂亮,但很简单。

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(MDN)。

我通常的代码是:

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