2017-06-22 42 views
-2

在以下代碼中的延遲的陣列的顯示索引,我試圖保持超時但它不工作。我發送數組並期待3秒延遲的數組索引。與3秒

function displayIndex(arr){ // array as input 
    for(var i=0;i<arr.length; i++){ 
     SetTimeout(function(){ 
      console.log(i); // always returns 4 
     },3000); 
    } 
} 

displayIndex([10,20,30,40]) 

更新:

var arr = [10,20,30,40]; 
function displayIndex(arr){ // array as input 
    for(var i=0;i<arr.length; i++){ 
    setTimeout(function() { 
     var currentI = i; //Store the current value of `i` in this closure 
     console.log(currentI); 
    }, 3000); 
    } 
} 

displayIndex(arr); // still prints all 4. 

此外,試圖

arr.forEach(function(curVal, index){ 
    setTimeout(function(){ 
    console.log(index); 
    },3000); 
}); // prints 0 1 2 3 but I do not see 3 secs gap between each display, rather one 3 sec delay before everything got displayed. 
+1

'setTimeout',而不是'setTimeout' JavaScript是一種區分大小寫的語言 – MrNew

回答

0

使用此:

function displayIndex(arr){ // array as input 
    var i=0; 
    var current; 
    run=setInterval(function(){ // set function inside a variable to stop it later 
     if (i<arr.length) { 
      current=arr[i]; // Asign i as vector of arr and put in a variable 'current' 
      console.log(current); 
      i=i+1; // i increasing 
     } else { 
      clearInterval(run); // This function stops the setInterval when i>=arr.lentgh 
     } 
    },3000);  
} 
displayIndex([10,20,30,40]); 

1:如果使用setTimeoutsetInterval功能for這是一個問題「職高裏這一切都是循環的方式(前兩個是與循環時間間隔)。 Aaand setTimeout只需運行一次代碼。

注:setInterval需要一個函數來阻止它clearInterval,所以這就是爲什麼我把一個if內。

第二:您沒有設置currentIiarr運營商的向量。當你運行一個數組的格式爲:arr[currentI],例如。

疑問?

+1

它的工作原理毫無疑問,謝謝?!你。 – ram

0

SetTimeout應該setTimeout。這是區分大小寫的。

你一次全部設置4個超時。既然你遞增的i每個循環的價值,這將是4在循環的結束。

我真的不知道你想做什麼,但也許你想要的嗎?

setTimeout(function() { 
    var currentI = i; //Store the current value of `i` in this closure 
    console.log(currentI); 
}, 3000); 
0

之所以它的工作不正常:

案例1:在第一個片段,setTimeout()是增加的功能事件隊列後,主線程沒有更多的代碼留給執行要執行。 i變量作爲參考被傳遞,因此每次調用都會打印上次修改後的值,因爲它是通過引用傳遞的。情況2:在這種情況下,由於您傳遞了4個顯式引用,所以這些值是不同的,但執行順序相同(即,同步和即時)。

原因:setTimeout()函數總是將傳遞給隊列的函數作爲最低保證,使其以延遲時間間隔運行。但是,如果函數之前的隊列中存在代碼,或者主線程中有任何其他代碼,則延遲時間會更長。

解決方法:如果你不實現阻斷代碼的行爲,我會建議使用的process.hrtime()爲瀏覽器模擬(應該有window對象上的計時方法,寫一個while循環,明確循環,直到第二經過

建議:我,爲什麼你需要在代碼,阻止有些困惑

+0

推理是有幫助的,我不需要任何具體的阻止代碼,但我只是嘗試這個算法使用javascript,直到@gabad的sol才能算出來。我想你的建議也由nodejs組成。會檢查。 TY。 – ram