我有一个数组,我使用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秒),然后继续遍历数组的其余部分。
答案 0 :(得分:4)
您无法在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
}
}
&#13;
<!-- 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>
&#13;
答案 1 :(得分:1)
与T.J. Crowder's answer类似,但使用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
数组,因此您可能需要先复制它。
答案 2 :(得分:1)
您无法在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);
}
}
答案 3 :(得分:0)
编写一个睡眠功能,然后调用它。 每5个元素应为a(5 -1的倍数) 因为我从0开始。
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()) {
}
}
答案 4 :(得分:0)
宾: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);
});