【问题标题】:Delay loop by 1 second延迟循环 1 秒
【发布时间】:2013-10-02 08:55:58
【问题描述】:

我需要每秒延迟一个循环,我需要计算循环迭代了多少次,一旦它与长度相比达到 3 的整除数,暂停一秒钟,然后继续循环。

var callsPerSecond = 500;
var len = 1900;
var delay = 1500;
var timeout;

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
    $('#log').append('<li>called</li>'); //  your code here
    i++; //  increment the counter
    if (i < ((len - (i % callsPerSecond)) / callsPerSecond)) { //  if the counter < 10, call the loop function
      myLoop(); //  ..  again which will trigger another 
    } //  ..  setTimeout()
    console.log(i);
  }, 500)
}

myLoop();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="log"></ul>

所以我应该在我的日志中得到 1900 foos,延迟一秒,3 次,因为 1900 可以被 500 整除 3 次。

我哪里错了? :(

【问题讨论】:

    标签: javascript jquery loops delay settimeout


    【解决方案1】:

    这段代码做你想做的事:

    var callsPerSecond = 500;
    var len = 1900;
    var delay = 1000;
    
    function myLoop(i) {
      while (i < len) {
        i++;
        console.log('foo' + i);
        if (i % callsPerSecond == 0) {
          setTimeout(function() {
            myLoop(i);
          }, delay);
          break;
        }
      }
    };
    
    myLoop(0);

    当i能被callsPersecond整除时,1000ms后再次调用myLoop函数并继续计数。

    【讨论】:

      【解决方案2】:

      如果我理解你的问题,这就是你的解决方案:

      var callsPerSecond = 500;
      var len = 1900;
      var delay = 1000;
      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
      
          if (i < ((len - (i % callsPerSecond)) / callsPerSecond)) { //  if the counter < 10, call the loop function
            $('#log').append('<li>called</li>'); //  your code here
      
          } //  ..  setTimeout()
      
          myLoop(); //  ..  again which will trigger another 
          console.log('foo' + i);
          i++; //  increment the counter
        }, delay)
      }
      
      myLoop();
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <ul id="log"></ul>

      【讨论】:

      • 感谢您的回复,它确实有效,但是 Ruudts 的回答看起来更好:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      相关资源
      最近更新 更多