[英]Javascript Add delay every 5th time in for loop
我有一个数组,并且正在使用for循环来遍历它,如下所示:
var test=['1','2','3','4','5','6','7','8','9','10','11','12','13'];
for(var i=0; i<test.length;i++){
console.log(test[i]);
}
现在,我想知道如何在数组循环中的每第5个项目中设置一个延迟(5秒),然后继续遍历数组的其余部分。
您实际上不能延迟 JavaScript中的代码(嗯,不是很合理),但是可以安排它稍后运行,然后让当前任务完成。 在浏览器和某些非浏览器环境中,这是通过setTimeout
或setInterval
。
在您的情况下, setTimeout
可能最有意义:
var test=['1','2','3','4','5','6','7','8','9','10','11','12','13'];
var i =0;
loop();
function loop() {
var max = Math.min(i + 5, test.length);
var j;
for (j = i; j < max; ++j, ++i) {
console.log(test[j]);
}
if (j < test.length) {
setTimeout(loop, 5000); // 5000ms = 5 second
}
}
实时示例:( 使用较短的延迟)
var test = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']; var i = 0; loop(); function loop() { var max = Math.min(i + 5, test.length); var j; for (j = i; j < max; ++j, ++i) { snippet.log(test[j]); } if (j < test.length) { setTimeout(loop, 1000); // 1000ms = 1 second } }
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
与TJ Crowder的答案类似,但使用splice
来进行数组数学运算:
var test=['1','2','3','4','5','6','7','8','9','10','11','12','13'];
function processBatchesOfFive() {
var fiveItemBatch = test.splice(0, 5);
// process the batch here
console.log('Now processing: ' + fiveItemBatch);
if(test.length){
setTimeout(processBatchesOfFive, 1000); // modify delay here
}
}
它在起作用: http : //jsbin.com/nuneyu/1/edit?js,console
注意:此版本会更改test
数组,因此您可能需要先对其进行复制。
您无法以任何有用的方式暂停Javascript中的循环。 将工作分为一次显示五个项目,并使用setTimeout
在延迟后开始下一部分:
var test = ['1','2','3','4','5','6','7','8','9','10','11','12','13']; var index = 0; showItems(); function showItems() { for (var i = 0; i < 5 && index < test.length; i++, index++){ console.log(test[index]); } if (index < test.length) { window.setTimeout(showItems, 5000); } }
编写一个函数使其进入睡眠状态,然后调用它。 当我从0开始时,每个第5个元素应为a(5 -1的倍数)。
var test=['1','2','3','4','5','6','7','8','9','10','11','12','13'];
for(var i=0; i<test.length;i++){
if((i+1)%5 == 0)
sleep(5000);
console.log(test[i]);
}
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
Bin: http : //jsbin.com/yuheziwozi/1/edit?js,console
var test=['1','2','3','4','5','6','7','8','9','10','11','12','13'];
test.forEach(function(num,index){
setTimeout(function(){
console.log(num);
},(parseInt(index/5))*5000);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.