2017-10-18 88 views
1

我有以下代碼來追加批量大小爲10的元素數組中的iframe,每個批次的時間間隔爲10秒。批處理是一個數組,它有一個JSON對象,每個批處理都有開始和結束索引。追加功能將帶有代碼的iframe附加到DOM。setTimeout函數意外的行爲

當前行爲: JS等待10秒鐘,並一起追加所有iframe,同時調用追加函數,而不用等待每批10秒。

預期行爲: JS在追加每個批處理或每個追加函數調用之前等待10秒鐘。

batches.forEach(function (x) { 
    setTimeout(function() { 
     append(x, elements); 
     console.log('appending'+x); 
    }, 10000); 
}); 

任何想法爲什麼會發生這種情況?

+0

相關:https://stackoverflow.com/q/45767325/5894241 – Nisarg

+1

你的foreach循環只是遍歷所有元素而不停止。所以它會很快爲每個元素創建一個setTimeout。然後他們等待10秒鐘,然後立刻執行所有操作。如果你希望他們在不同的時間執行,那麼你必須給他們每個不同的延遲。 – RJM

回答

5

setTimeout所以你的代碼是

setTimeout(..., 10000) 
setTimeout(..., 10000) 
setTimeout(..., 10000) 
// etc 

相當於每個超時通話被設置爲大致執行的同時,從現在開始10秒不會暫停執行。

你將不得不在每次迭代中增加超時。事情是這樣的......

batches.forEach((x, i) => { // where "i" is the current, zero-based index 
    setTimeout(() => { 
    // etc 
    }, 10000 * (i + 1)) 
}) 
0

你可以創建一個函數來處理這樣的批次:

function processBatch(batches, delay){ 
    setTimeout(function(){ 
     // get the first element/child in batches 
     var batch = batches[0]; 
     // process your batch the way you want it 
     console.log(batch); 
     // remove the already processed batch 
     batches.splice(0, 1); 
     if (batches.length > 0){ 
      // process the remainder batches 
      processBatch(batches, delay) 
     } else { 
      console.log('done'); 
     } 
    }, delay) 
} 

調用它:

var batches = [1, 2, 3, 4]; 
processBatch(batches, 100000); 

看到它在行動:https://jsfiddle.net/pa64vqxr/ (別忘了打開瀏覽器控制檯)