延迟循环1秒

问题描述 投票:0回答:2

我需要每秒延迟一个循环,我需要计算循环重复多少次,一旦循环达到与长度相比为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个foo,延迟一秒,即3倍,因为1900可以除以500 3倍。

我要去哪里错了? :(

javascript jquery loops delay settimeout
2个回答
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);

当我可以被callsPersecond整除时,它将在1000ms之后再次调用myLoop函数,并继续计数。


1
投票

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

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>
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.