2015-05-31 46 views
1

這會產生2秒的延遲並運行循環。我需要爲每次迭代創建2秒的延遲,而不僅僅是一次。如何使用setTimeout爲每次迭代添加延遲?

var myArray = ['test1','test2','test3']; 

function doSetTimeout(index) { 
    setTimeout(function() { console.log(myArray[index]) }, 2000); 
} 

var index; 
for (index = 0; index < myArray.length; ++index) {  
    doSetTimeout(index) 
} 

預期的結果將是:

test1 
(2 second delay) 
test2 
(2 second delay) 
test3 
+0

只需乘以你的延遲爲什麼不使用'setInterval',並從那裏處理您的隊列,一個在FIME? – some

回答

1

由索引

var myArray = ['test1','test2','test3']; 

function doSetTimeout(index) { 
    setTimeout(function() { console.log(myArray[index]) }, index * 2000; 
} 

var index; 
for (index = 0; index < myArray.length; ++index) { 
    doSetTimeout(index) 
}