延迟循环 1 秒
Delay loop by 1 second
我需要每秒延迟一个循环,我需要计算循环迭代了多少次,一旦它达到与长度相比的 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>
相关文章:
- 带有延迟的循环每次应运行5次
- jQuery延迟了ajax调用的循环
- jQuery通过步骤的自排队循环来解决延迟问题
- Javascript:延迟在html5画布上循环绘制
- 如何在Javascript中延迟for循环执行
- 使循环滑块具有延迟
- 循环中的多个 JavaScript 延迟
- jquery .each 循环来执行每个数组项,它们之间有延迟
- foreach循环每次迭代之间的延迟
- 在javascript for循环的迭代之间应用延迟
- 在延迟时运行javascript for循环
- 将for循环从完成延迟到返回API调用
- jquery在循环中延迟
- 如何通过宽松来增加javascript循环延迟
- 对于下一次迭代之前的循环延迟
- JQuery中的循环延迟
- 对于没有setTimeout的循环延迟
- 循环延迟超时问题
- 循环延迟
- 对话框 ajax 加载动画效果 - 需要循环延迟、睡眠