[英]Build list of time delayed function calls within loop
我正在嘗試列出一個函數調用列表,並按一定的時間間隔分隔。 下面的代碼當前占用每個函數調用的最后一項。
當前代碼打印:itemThree,itemThree,itemThree-每個間隔十秒
所需的代碼打印出來:itemOne,itemTwo,itemThree-每個間隔十秒
//Declare variables
var itemList = ["itemOne", "itemTwo", "itemThree"];
var timerInterval = 0;
//Loop through the itemList and build a list of functions calls
//Each function call will be lined up with a 10 second gap
for(index = 0; index < itemList.length; index++) {
var item = itemList[index];
setTimeout(function() { doSomethingWithItem(item); }, timerInterval);
timerInterval = timerInterval + 10000;
}
//Print passed in item
var doSomethingWithItem = function(item) {
console.log(item);
}
我正在嘗試列出計時器延遲的函數調用。 我將如何更改上面的代碼,或者有更好的解決方案? 感謝您的幫助。
JavaScript通過引用傳遞值,並且在超時觸發時, index
將達到其最大值,因此將始終顯示“ itemThree”。 要解決此問題,您需要為循環變量創建另一個作用域,以使其不被外部作用域更改。
//Loop through the itemList and build a list of functions calls
//Each function call will be lined up with a 10 second gap
for(index = 0; index < itemList.length; index++) {
// creating new scope for index to live in
(function(num) {
var item = itemList[num];
setTimeout(function() { doSomethingWithItem(item); }, timerInterval);
timerInterval = timerInterval + 10000;
})(index);
}
我在這種情況下使用的一種方法是在偽遞歸循環中使用立即調用的函數表達式 ,一次從列表中提取元素:
//Declare variables
var itemList = ["itemOne", "itemTwo", "itemThree"];
var timerInterval = 10000;
(function loop() {
var item = itemList.shift();
if (item) {
setTimeout(function() {
doSomethingWithItem(item);
loop()
}, timerInterval);
}
})();
//Print passed in item
var doSomethingWithItem = function(item) {
console.log(item);
}
如果沒有for
循環,則可以避免在每個回調過程中item
變量具有最后分配的值的問題。
使用setTimeout
的偽遞歸使用,還可以避免一次排隊多個計時器。 我將這種用法稱為偽遞歸,因為盡管看起來loop
在調用自身,但實際上setTimeout
調用只是將回調添加到要從瀏覽器事件處理循環觸發的函數隊列中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.