2013-05-02 48 views
0

我試圖用Javascript顯示一些文本,但取決於字符串的長度,只有幾秒鐘。我已經根據文章How to limit the number of iterations done by setInterval的答案創建了一個非常簡單的示例。但對我來說不起作用:顯示Javascript的元素一個接一個地站立一段時間,具體取決於長度

<script> 
var iterations = 0, 
    data = ['a','bbbbbbbb','c'], 
    interval = setInterval(foo, 4000); 

function foo() { 
    console.log(data[iterations]); 
    iterations++; 
    if (iterations >= 4){ 
     clearInterval(interval); 
    }else if(iterations == 1){ 
     //we want to make time longer in this iteration. 
     clearInterval(interval); 
     var interval = setInterval(foo, 8000); 
    } 
} 
</script> 

我想再次拿作爲輸出「A」 4秒鐘後,「BBBBBBBB」後8和「c」 4後。

正如你可以看到我有一個數組與3個元素。對於迭代1,它應該等待更多的時間,但不會。對於所有情況等待4秒鐘,我們有一個無限循環。

我已經檢查了其他功能,如break和setInterval函數無效。

它會是一個更智能的解決方案,而不是基於循環?非常感謝。

回答

1

您在「foo」中重新聲明區間爲局部變量。

改變此密碼塊從:

else if(iterations == 1){ 
    //we want to make time longer in this iteration. 
    clearInterval(interval); 
    var interval = setInterval(foo, 8000); 
} 

向該(沒有 '變種' 關鍵字):

else if(iterations == 1){ 
    //we want to make time longer in this iteration. 
    clearInterval(interval); 
    interval = setInterval(foo, 8000); 
} 
相關問題