簡體   English   中英

JavaScript在for循環中每隔5次添加延遲

[英]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中的代碼(嗯,不是很合理),但是可以安排它稍后運行,然后讓當前任務完成。 在瀏覽器和某些非瀏覽器環境中,這是通過setTimeoutsetInterval

在您的情況下, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM