【问题标题】:How do I add a delay in a JavaScript loop?如何在 JavaScript 循环中添加延迟?
【发布时间】:2021-05-30 08:16:18
【问题描述】:

我想在 while 循环中添加延迟/睡眠:

我试过这样:

alert('hi');

for(var start = 1; start < 10; start++) {
  setTimeout(function () {
    alert('hello');
  }, 3000);
}

只有第一种情况为真:显示alert('hi')后,等待3秒,然后显示alert('hello'),然后alert('hello')不断重复。

我想要的是,在alert('hello')alert('hi') 之后显示3 秒之后,它需要等待3 秒第二次alert('hello') 等等。

【问题讨论】:

  • for(var i=0; i
  • const setTimeOutFn= async()=>{ for(var start = 0; start { setTimeout(() => { console.log('hello', start); res() }, 3000); }) } }

标签: javascript loops sleep


【解决方案1】:

setTimeout() 函数是非阻塞的,会立即返回。因此,您的循环将非常快速地迭代,并且它将快速连续地一个接一个地启动 3 秒超时触发器。这就是为什么您的第一个警报会在 3 秒后弹出,然后所有其他警报都会连续出现,没有任何延迟。

您可能想要使用类似的东西:

var i = 1;                  //  set your counter to 1

function myLoop() {         //  create a loop function
  setTimeout(function() {   //  call a 3s setTimeout when the loop is called
    console.log('hello');   //  your code here
    i++;                    //  increment the counter
    if (i < 10) {           //  if the counter < 10, call the loop function
      myLoop();             //  ..  again which will trigger another 
    }                       //  ..  setTimeout()
  }, 3000)
}

myLoop();                   //  start the loop

您还可以通过使用自调用函数将迭代次数作为参数传递给它:

(function myLoop(i) {
  setTimeout(function() {
    console.log('hello'); //  your code here                
    if (--i) myLoop(i);   //  decrement i and call myLoop again if i > 0
  }, 3000)
})(10);                   //  pass the number of iterations as an argument

【讨论】:

  • 不会使用递归来实现这个最终会发生堆栈溢出吗?如果你想做一百万次迭代,有什么更好的方法来实现呢?也许 setInterval 然后清除它,就像下面 Abel 的解决方案?
  • @Adam:我的理解是,由于 setTimeout 是非阻塞的,所以这不是回避 - 每次 setTimeout 后堆栈窗口都会关闭,并且只有一个 setTimeout 等待执行......对吗?
  • 当迭代像for in循环这样的对象时,这将如何工作?
  • @vsync 查看Object.keys()
  • @joey 你把setTimeoutsetInterval 混淆了。调用回调时,超时被隐式销毁。
【解决方案2】:

因为 ES7 有一个更好的方法来等待一个循环:

// Returns a Promise that resolves after "ms" Milliseconds
const timer = ms => new Promise(res => setTimeout(res, ms))

async function load () { // We need to wrap the loop into an async function for this to work
  for (var i = 0; i < 3; i++) {
    console.log(i);
    await timer(3000); // then the created Promise can be awaited
  }
}

load();

当引擎到达await 部分时,它会设置超时并停止async function 的执行。然后当超时完成时,执行将在该点继续。这非常有用,因为您可以延迟 (1) 嵌套循环,(2) 有条件地,(3) 嵌套函数:

async function task(i) { // 3
  await timer(1000);
  console.log(`Task ${i} done!`);
}

async function main() {
  for(let i = 0; i < 100; i+= 10) {
    for(let j = 0; j < 10; j++) { // 1
      if(j % 2) { // 2
        await task(i + j);
      }
    }
  }
}
    
main();

function timer(ms) { return new Promise(res => setTimeout(res, ms)); }

Reference on MDN

虽然 NodeJS 和现代浏览器现在支持 ES7,但您可能希望 transpile it with BabelJS 以便它可以在任何地方运行。

【讨论】:

  • 它对我来说很好用。我只想问,如果我想打破循环,使用等待时我该怎么做?
  • @sachin break; 也许?
  • 感谢您的解决方案。使用所有现有的控制结构而不需要发明延续是很好的。
  • 这仍然只是创建各种计时器,它们会在不同的时间而不是按顺序解决?
  • 这是迄今为止最好的解决方案,应该是公认的答案。接受的答案是hacky,不应该用于任何事情。
【解决方案3】:

如果使用 ES6,您可以使用 for 循环来实现:

for (let i = 1; i < 10; i++) {
  setTimeout(function timer() {
    console.log("hello world");
  }, i * 3000);
}

它为每个迭代声明i,这意味着超时是+1000之前的值。这样,传递给setTimeout的正是我们想要的。

【讨论】:

  • 谢谢!我自己不会想到这种方法。实际块范围。想象一下……
  • 我相信这与stackoverflow.com/a/3583795/1337392中描述的答案具有相同的内存分配问题
  • @Flame_Phoenix 什么内存分配问题?
  • setTimeout 调用在循环内同步计算i*3000 参数的值,并将其按值传递给setTimeoutlet 的使用是可选的,与问题和答案无关。
  • @Flame_Phoenix 提到此代码存在问题。基本上在第一次通过时,您创建计时器,然后立即一次又一次地重复循环,直到循环按条件结束 (i &lt; 10),因此您将有多个计时器并行工作,这会创建内存分配,并且在大量迭代时情况会更糟。
【解决方案4】:

试试这样的:

var i = 0, howManyTimes = 10;

function f() {
  console.log("hi");
  i++;
  if (i < howManyTimes) {
    setTimeout(f, 3000);
  }
}

f();

【讨论】:

  • 谢谢,你让我开心!
【解决方案5】:

另一种方法是将超时时间相乘,但请注意,这不像睡眠。循环后的代码会立即执行,只有回调函数的执行被延迟。

for (var start = 1; start < 10; start++)
    setTimeout(function () { alert('hello');  }, 3000 * start);

第一个超时设置为3000 * 1,第二个设置为3000 * 2,以此类推。

【讨论】:

  • 值得指出的是,使用此方法无法在函数中可靠地使用start
  • 不好的做法 - 不必要的内存分配。
  • 支持创造力,但这是非常糟糕的做法。 :)
  • 为什么这是一种不好的做法,为什么会出现内存分配问题?这个答案会遇到同样的问题吗? stackoverflow.com/a/36018502/1337392
  • @Flame_Phoenix 这是一种不好的做法,因为程序将为每个循环保留一个计时器,所有计时器同时运行。所以如果有1000次迭代,一开始会有1000个定时器同时运行。
【解决方案6】:

这会起作用

for (var i = 0; i < 10; i++) {
  (function(i) {
    setTimeout(function() { console.log(i); }, 100 * i);
  })(i);
}

试试这个小提琴:https://jsfiddle.net/wgdx8zqq/

【讨论】:

  • 这确实会在同一时间触发所有超时调用
  • 我唯一要说的是,我已经破解了这种方法,使用了$.Deferred,但让它起作用是一些不同的场景,给你点赞..!
【解决方案7】:

我认为你需要这样的东西:

var TimedQueue = function(defaultDelay){
    this.queue = [];
    this.index = 0;
    this.defaultDelay = defaultDelay || 3000;
};

TimedQueue.prototype = {
    add: function(fn, delay){
        this.queue.push({
            fn: fn,
            delay: delay
        });
    },
    run: function(index){
        (index || index === 0) && (this.index = index);
        this.next();
    },
    next: function(){
        var self = this
        , i = this.index++
        , at = this.queue[i]
        , next = this.queue[this.index]
        if(!at) return;
        at.fn();
        next && setTimeout(function(){
            self.next();
        }, next.delay||this.defaultDelay);
    },
    reset: function(){
        this.index = 0;
    }
}

测试代码:

var now = +new Date();

var x = new TimedQueue(2000);

x.add(function(){
    console.log('hey');
    console.log(+new Date() - now);
});
x.add(function(){
    console.log('ho');
    console.log(+new Date() - now);
}, 3000);
x.add(function(){
    console.log('bye');
    console.log(+new Date() - now);
});

x.run();

注意:使用警报会停止 javascript 的执行,直到您关闭警报。 它可能比您要求的要多,但这是一个强大的可重用解决方案。

【讨论】:

    【解决方案8】:

    我可能会使用setInteval。像这样,

    var period = 1000; // ms
    var endTime = 10000;  // ms
    var counter = 0;
    var sleepyAlert = setInterval(function(){
        alert('Hello');
        if(counter === endTime){
           clearInterval(sleepyAlert);
        }
        counter += period;
    }, period);
    

    【讨论】:

    • SetTimeout 比 settinterval 好很多。 google一下就知道了
    • 我用谷歌搜索了一下,什么也没找到,为什么 setInterval 不好?你能给我们一个链接吗?还是一个例子?谢谢
    • 我猜the pointSetInterval() 即使在出现一些错误或阻塞的情况下也会不断产生“线程”。
    【解决方案9】:

    function waitforme(ms)  {
      return new Promise( resolve => { setTimeout(resolve, ms); });
    }
    
    async function printy()  {
    
      for (let i=0; i < 10 ; i++) {
    
        await waitforme(1000); // loop will be halted here until promise is resolved
    
        console.log(i);
      }
    
      console.log("I Ran after the loop finished :)");
    }
    
    
    printy();

    【讨论】:

      【解决方案10】:

      在 ES6 (ECMAScript 2015) 中,您可以使用 generator 和间隔进行延迟迭代。

      生成器是 ECMAScript 6 的一个新特性,它是可以被 暂停和恢复。调用 genFunc 不会执行它。相反,它 返回一个所谓的生成器对象,让我们控制 genFunc 的 执行。 genFunc() 最初在其开始时暂停 身体。方法 genObj.next() 继续执行 genFunc, 直到下一次产量。 (Exploring ES6)


      代码示例:

      let arr = [1, 2, 3, 'b'];
      let genObj = genFunc();
      
      let val = genObj.next();
      console.log(val.value);
      
      let interval = setInterval(() => {
        val = genObj.next();
        
        if (val.done) {
          clearInterval(interval);
        } else {
          console.log(val.value);
        }
      }, 1000);
      
      function* genFunc() {
        for(let item of arr) {
          yield item;
        }
      }

      因此,如果您使用的是 ES6,那是实现延迟循环的最优雅方式(在我看来)。

      【讨论】:

        【解决方案11】:

        在我看来,在循环中添加延迟的更简单、最优雅的方法是这样的:

        names = ['John', 'Ana', 'Mary'];
        
        names.forEach((name, i) => {
         setTimeout(() => {
          console.log(name);
         }, i * 1000);  // one sec interval
        });
        

        【讨论】:

          【解决方案12】:

          我使用 Bluebird 的 Promise.delay 和递归来做到这一点。

          function myLoop(i) {
            return Promise.delay(1000)
              .then(function() {
                if (i > 0) {
                  alert('hello');
                  return myLoop(i -= 1);
                }
              });
          }
          
          myLoop(3);
          &lt;script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"&gt;&lt;/script&gt;

          【讨论】:

            【解决方案13】:

            在 ES6 中,您可以执行以下操作:

             for (let i = 0; i <= 10; i++){       
                 setTimeout(function () {   
                    console.log(i);
                 }, i*3000)
             }

            在 ES5 中你可以这样做:

            for (var i = 0; i <= 10; i++){
               (function(i) {          
                 setTimeout(function () {   
                    console.log(i);
                 }, i*3000)
               })(i);  
             }

            原因是,let 允许您声明仅限于块语句范围或使用它的表达式的变量,这与 var 关键字不同,它在全局或本地定义变量整个函数,无论块范围如何。

            【讨论】:

              【解决方案14】:

              你可以使用 RxJS interval operator。 Interval 每 x 秒发出一个整数,take 指定它必须发出数字的次数

              Rx.Observable
                .interval(1000)
                .take(10)
                .subscribe((x) => console.log(x))
              &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"&gt;&lt;/script&gt;

              【讨论】:

                【解决方案15】:

                据我所知,setTimeout 函数是异步调用的。您可以做的是将整个循环包装在一个异步函数中并等待包含 setTimeout 的Promise,如下所示:

                var looper = async function () {
                  for (var start = 1; start < 10; start++) {
                    await new Promise(function (resolve, reject) {
                      setTimeout(function () {
                        console.log("iteration: " + start.toString());
                        resolve(true);
                      }, 1000);
                    });
                  }
                  return true;
                }
                

                然后你像这样调用它:

                looper().then(function(){
                  console.log("DONE!")
                });
                

                请花点时间好好了解异步编程。

                【讨论】:

                  【解决方案16】:

                  无功能解决方案

                  我参加聚会有点晚了,但是有一个不使用任何函数的解决方案:

                  alert('hi');
                  
                  for(var start = 1; start < 10; start++) {
                    setTimeout(() => alert('hello'), 3000 * start);
                  }
                  

                  【讨论】:

                  • 这将以 3 秒为间隔安排 10 个警报,而不是在 alert() 清除后的 3 秒等待时间。如果第一个 alert() 没有在 30 秒内清除,其余的将不会在它们之间暂停。
                  【解决方案17】:

                  只是想我也会在这里发布我的两分钱。这个函数运行一个有延迟的迭代循环。见this jsfiddle。函数如下:

                  function timeout(range, time, callback){
                      var i = range[0];                
                      callback(i);
                      Loop();
                      function Loop(){
                          setTimeout(function(){
                              i++;
                              if (i<range[1]){
                                  callback(i);
                                  Loop();
                              }
                          }, time*1000)
                      } 
                  }
                  

                  例如:

                  //This function prints the loop number every second
                  timeout([0, 5], 1, function(i){
                      console.log(i);
                  });
                  

                  相当于:

                  //This function prints the loop number instantly
                  for (var i = 0; i<5; i++){
                      console.log(i);
                  }
                  

                  【讨论】:

                    【解决方案18】:

                    除了 10 年前公认的答案之外,使用更现代的 Javascript 可以使用 async/await/Promise() 或生成器函数来实现正确行为。 (其他答案中建议的不正确行为是设置一系列 3 秒警报,而不管“接受”alert() - 或完成手头的任务)

                    使用async/await/Promise()

                    alert('hi');
                    
                    (async () => {
                      for(let start = 1; start < 10; start++) {
                        await new Promise(resolve => setTimeout(() => {
                          alert('hello');
                          resolve();
                        }, 3000));
                      }
                    })();

                    使用生成器函数:

                    alert('hi');
                    
                    let func;
                    
                    (func = (function*() {
                      for(let start = 1; start < 10; start++) {
                        yield setTimeout(() => {
                          alert('hello');
                          func.next();
                        }, 3000);
                      }
                    })()).next();

                    【讨论】:

                      【解决方案19】:

                          var startIndex = 0;
                          var data = [1, 2, 3];
                          var timeout = 1000;
                      
                          function functionToRun(i, length) {
                            alert(data[i]);
                          }
                      
                          (function forWithDelay(i, length, fn, delay) {
                            setTimeout(function() {
                              fn(i, length);
                              i++;
                              if (i < length) {
                                forWithDelay(i, length, fn, delay);
                              }
                            }, delay);
                          })(startIndex, data.length, functionToRun, timeout);

                      Daniel Vassallo 答案的修改版本,将变量提取到参数中以使函数更可重用:

                      首先让我们定义一些基本变量:

                      var startIndex = 0;
                      var data = [1, 2, 3];
                      var timeout = 3000;
                      

                      接下来,您应该定义要运行的函数。这将传递 i,循环的当前索引和循环的长度,以防你需要它:

                      function functionToRun(i, length) {
                          alert(data[i]);
                      }
                      

                      自执行版本

                      (function forWithDelay(i, length, fn, delay) {
                         setTimeout(function () {
                            fn(i, length);
                            i++;
                            if (i < length) {
                               forWithDelay(i, length, fn, delay); 
                            }
                        }, delay);
                      })(startIndex, data.length, functionToRun, timeout);
                      

                      功能版

                      function forWithDelay(i, length, fn, delay) {
                         setTimeout(function () {
                            fn(i, length);
                            i++;
                            if (i < length) {
                               forWithDelay(i, length, fn, delay); 
                            }
                        }, delay);
                      }
                      
                      forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it
                      

                      【讨论】:

                      • 不错,如何在没有全局变量的情况下将数据传递给函数
                      【解决方案20】:

                      试试这个

                       var arr = ['A','B','C'];
                       (function customLoop (arr, i) {
                          setTimeout(function () {
                          // Do here what you want to do.......
                          console.log(arr[i]);
                          if (--i) {                
                            customLoop(arr, i); 
                          }
                        }, 2000);
                      })(arr, arr.length);
                      

                      结果

                      A // after 2s
                      B // after 2s
                      C // after 2s
                      

                      【讨论】:

                        【解决方案21】:
                        /* 
                          Use Recursive  and setTimeout 
                          call below function will run loop loopFunctionNeedCheck until 
                          conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay 
                          reRunAfterMs miliseconds and continue loop
                          tested code, thanks
                        */
                        
                        function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
                         loopFunctionNeedCheck) {
                            loopFunctionNeedCheck();
                            var result = conditionCheckAfterRunFn();
                            //check after run
                            if (!result) {
                                setTimeout(function () {
                                    functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
                                }, reRunAfterMs);
                            }
                            else  console.log("completed, thanks");    
                                    //if you need call a function after completed add code call callback in here
                        }
                        
                        //passing-parameters-to-a-callback-function
                        // From Prototype.js 
                        if (!Function.prototype.bind) { // check if native implementation available
                            Function.prototype.bind = function () {
                                var fn = this, args = Array.prototype.slice.call(arguments),
                                    object = args.shift();
                                return function () {
                                    return fn.apply(object,
                                      args.concat(Array.prototype.slice.call(arguments)));
                                };
                            };
                        }
                        
                        //test code: 
                        var result = 0; 
                        console.log("---> init result is " + result);
                        var functionNeedRun = function (step) {           
                           result+=step;    
                               console.log("current result is " + result);  
                        }
                        var checkResultFunction = function () {
                            return result==100;
                        }  
                        
                        //call this function will run loop functionNeedRun and delay 500 miliseconds until result=100    
                        functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));
                        
                        //result log from console:
                        /*
                        ---> init result is 0
                        current result is 5
                        undefined
                        current result is 10
                        current result is 15
                        current result is 20
                        current result is 25
                        current result is 30
                        current result is 35
                        current result is 40
                        current result is 45
                        current result is 50
                        current result is 55
                        current result is 60
                        current result is 65
                        current result is 70
                        current result is 75
                        current result is 80
                        current result is 85
                        current result is 90
                        current result is 95
                        current result is 100
                        completed, thanks
                        */
                        

                        【讨论】:

                        • 你的函数名太可怕了,这就是这段代码很难阅读的主要原因。
                        【解决方案22】:

                        以下是我如何创建一个无限循环,该循环在特定条件下会中断:

                          // Now continuously check the app status until it's completed, 
                          // failed or times out. The isFinished() will throw exception if
                          // there is a failure.
                          while (true) {
                            let status = await this.api.getStatus(appId);
                            if (isFinished(status)) {
                              break;
                            } else {
                              // Delay before running the next loop iteration:
                              await new Promise(resolve => setTimeout(resolve, 3000));
                            }
                          }
                        

                        这里的关键是创建一个新的通过超时解决的 Promise,并等待它的解决。

                        显然你需要 async/await 支持。在节点 8 中工作。

                        【讨论】:

                          【解决方案23】:

                          对于常用的“忘记正常循环”并使用“setInterval”的这种组合包括“setTimeOut”:就像这样(来自我的实际任务)。

                                  function iAsk(lvl){
                                      var i=0;
                                      var intr =setInterval(function(){ // start the loop 
                                          i++; // increment it
                                          if(i>lvl){ // check if the end round reached.
                                              clearInterval(intr);
                                              return;
                                          }
                                          setTimeout(function(){
                                              $(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
                                          },50);
                                          setTimeout(function(){
                                               // do another bla bla bla after 100 millisecond.
                                              seq[i-1]=(Math.ceil(Math.random()*4)).toString();
                                              $("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
                                              $("#d"+seq[i-1]).prop("src",pGif);
                                              var d =document.getElementById('aud');
                                              d.play();                   
                                          },100);
                                          setTimeout(function(){
                                              // keep adding bla bla bla till you done :)
                                              $("#d"+seq[i-1]).prop("src",pPng);
                                          },900);
                                      },1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
                                  }
                          

                          PS:了解 (setTimeOut) 的实际行为:它们都将在同一时间开始“三个 bla bla bla 将在同一时刻开始倒计时”,因此请设置不同的超时时间来安排执行。

                          PS 2:计时循环的示例,但对于反应循环,您可以使用事件,promise async await ..

                          【讨论】:

                            【解决方案24】:

                            <!DOCTYPE html>
                            <html>
                            <body>
                            
                            <button onclick="myFunction()">Try it</button>
                            
                            <p id="demo"></p>
                            
                            <script>
                            function myFunction() {
                                for(var i=0; i<5; i++) {
                                	var sno = i+1;
                                   	(function myLoop (i) {          
                                         setTimeout(function () {   
                                         	alert(i); // Do your function here 
                                         }, 1000*i);
                                    })(sno);
                                }
                            }
                            </script>
                            
                            </body>
                            </html>

                            【讨论】:

                            • 请始终为您的代码 sn-ps 提供至少简短的描述,至少让其他人确保您解决问题。
                            • 不鼓励仅使用代码回答,因为它们没有为未来的读者提供太多信息,请对您所写的内容提供一些解释
                            【解决方案25】:
                               let counter =1;
                               for(let item in items) {
                                    counter++;
                                    setTimeout(()=>{
                                      //your code
                                    },counter*5000); //5Sec delay between each iteration
                                }
                            

                            【讨论】:

                            • 这忽略了在循环内有延迟的要求。只是以 5 秒的间隔设置一系列事件(不妨使用setInterval)。为了更好地理解问题,请使用alert 并等待 5 秒钟,然后点击 OK。下一个警报将立即显示,不会有任何延迟。
                            【解决方案26】:

                            你做到了:

                            console.log('hi')
                            let start = 1
                            setTimeout(function(){
                              let interval = setInterval(function(){
                                if(start == 10) clearInterval(interval)
                                start++
                                console.log('hello')
                              }, 3000)
                            }, 3000)
                            &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

                            【讨论】:

                            • 最好使用控制台日志而不是警报,关闭警报半分钟不是很有趣;)
                            • 是的。我懂了!但是请求是警报...huz
                            • 为什么要导入 jQuery?
                            • 抱歉……没必要……呵呵。我不知道发布内容...先这个。
                            • 另一个预设间隔忽略任务alert的答案,没有回答问题。
                            【解决方案27】:
                            var count = 0;
                            
                            //Parameters:
                            //  array: []
                            //  fnc: function (the business logic in form of function-,what you want to execute)
                            //  delay: milisecond  
                            
                            function delayLoop(array,fnc,delay){
                                if(!array || array.legth == 0)return false;
                                setTimeout(function(data){ 
                                    var data = array[count++];
                                    fnc && fnc(data);
                                    //recursion...
                                    if(count < array.length)
                                        delayLoop(array,fnc,delay);
                                    else count = 0;     
                                },delay);
                            }
                            

                            【讨论】:

                              【解决方案28】:
                              const autoPlayer = (arr = [1, 2, 3, 4, 5]) => {
                                // Base case:
                                if (arr.length < 1) return
                              
                                // Remove the first element from the array.
                                const item = arr.shift()
                              
                                // Set timout 
                                setTimeout(() => {
                                  console.log('Hello, world!', item)  // Visualisation.
                                  autoPlayer() // Call function again.
                                }, 1000) // Iterate every second.
                              }
                              

                              嘿,我知道这篇文章很老了,但是这段代码“循环”并使用递归方法为其添加了延迟。我认为您不能“实际上”根据从其他人那里读取各种 cmets 来延迟循环本身的迭代。也许这可以帮助某人!基本上该函数接受一个数组(在本例中)。在每次迭代中,都会调用 setTimeout Javascript 方法。当setTimeout 函数的计时器到期时,该函数会无限期地再次调用自身,但在每次调用时,数组都会变小,直到达到基本情况。我希望这可以帮助其他人。

                              【讨论】:

                                【解决方案29】:

                                这是我用来循环数组的函数:

                                function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){
                                
                                    if (i < theArray.length && typeof delayAmount == 'number'){
                                
                                        console.log("i "+i);
                                
                                        theFunction(theArray[i], i);
                                
                                        setTimeout(function(){
                                
                                            loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
                                    }else{
                                
                                        onComplete(i);
                                    }
                                }
                                

                                你可以这样使用它:

                                loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
                                    //Do something with item
                                }, function(i){
                                    //Do something once loop has completed
                                }
                                

                                【讨论】:

                                  【解决方案30】:

                                  这个脚本适用于大多数事情

                                  function timer(start) {
                                      setTimeout(function () { //The timer
                                          alert('hello');
                                      }, start*3000); //needs the "start*" or else all the timers will run at 3000ms
                                  }
                                  
                                  for(var start = 1; start < 10; start++) {
                                      timer(start);
                                  }
                                  

                                  【讨论】:

                                    猜你喜欢
                                    相关资源
                                    最近更新 更多