延迟循环 1 秒

Delay loop by 1 second

本文关键字:循环 延迟      更新时间:2023-09-26

我需要每秒延迟一个循环,我需要计算循环迭代了多少次,一旦它达到与长度相比的 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 次。

我哪里出错了?:(

此代码执行您想要的操作:

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 函数并继续计数。

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

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>