2013-06-04 39 views
4

我需要我的代碼運行x次的時間,然後在恢復之前暫停30秒左右。有任何想法嗎?運行setInterval幾次,然後暫停幾秒

myslidefunction(); 
var tid = setInterval(myslidefunction, 1000); 

function myslidefunction() { 
    setTimeout(function() { 
     //do stuff 
    }, 400); 
}; 
+0

爲什麼你不使用的setInterval(myslidefunction,1400)? – Stiger

回答

8

你可以保持運行計數,並使用normal_duration + 30000setTimeout延遲爲X + 1時間。

var runCount = 0, runsBeforeDelay = 20; 
function myslidefunction(){ 

    // .. stuff 

    runCount++; 
    var delay = 0; 
    if(runCount > runsBeforeDelay) { 
     runCount = 0; 
     delay = 30000; 
    } 
    setTimeout(myslidefunction, 400 + delay); 
}; 

// start it off 
setTimeout(myslidefunction, 1000); 
+0

難道你不想'setInterval()'? 'setTimeout()'只會運行一次。 –

+0

是啊,我在這裏正確使用了setTimeout .. – techfoobar

+0

@DerekHenderson他從函數本身調用setTimeOut。所以這是一種遞歸調用。 – sachinjain024

1
var counter = 0; 

var mySlideFunction = function(){ 

    /* your "do stuff" code here */ 

    counter++; 
    if(counter>=10){ 
     counter = 0; 
     setTimeout(mySlideFunction, 30000); 
    }else{ 
     setTimeout(mySlideFunction, 1000); 
    } 
} 

mySlideFunction(); 
+0

這樣你也可以選擇在任何給定的點停止迭代,而不是試圖用clearInterval()來計時。 – CodeMoose

相關問題