我需要每秒延迟一个循环,我需要计算循环迭代了多少次,一旦它与长度相比达到了 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函数并继续计数。
关于javascript - 延迟循环 1 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19133288/