2012-09-10 62 views
4

我正在創建一個應用程序來輪詢服務器的特定更改。我使用setTimeout自我調用函數。像這樣的東西基本上是:SetTimeTime可能太長?

<script type="text/javascript"> 
someFunction(); 

function someFunction() { 
    $.getScript('/some_script'); 
    setTimeout(someFunction, 100000); 
} 
</script> 

爲了使此輪詢服務器上較不密集,我希望有一個較長的超時間隔;也許在1min到2min的範圍內。有沒有什麼時候setTimeout的超時時間變得太長而不再正常工作?

+0

我不認爲它會接近您要放入的數字。 –

+1

可能的重複:http://stackoverflow.com/questions/3468607/why-does-settimeout-break-for-large-millisecond-delay-values – Richard

+0

正如Richard指出的那樣,對於你的問題有一個完美的答案,以防萬一你有真正的大超時(大於〜24天):http://stackoverflow.com/questions/3468607/why-does-settimeout-break-for-large-millisecond-delay-values#18182660 –

回答

2

setTimeout()對其延遲參數使用32位整數。因此,最大的是:

2147483647 

而不是使用遞歸setTimeout()我建議使用setInterval()

setInterval(someFunction, 100000); 

function someFunction() { 
    $.getScript('/some_script'); 
} 
+0

爲什麼downvote? – Curt

+0

我不同意有關遞歸setTimeout的setInterval。 setTimeout應該在一個if中,以防止它在需要停止時被再次調用。 https://zetafleet.com/blog/2010/04/why-i-consider-setinterval-to-be-harmful.html – LocalPCGuy

5

你在技術上確定。您可以有一個高達24.8611天的超時!如果你真的想。 setTimeout可以達到2147483647毫秒(32位整數的最大值,大約24天),但是如果它高於這個值,你會看到意外的行爲。請參閱Why does setTimeout() "break" for large millisecond delay values?

對於間隔,如輪詢,我推薦使用setInterval而不是遞歸setTimeout。 setInterval完全符合您的輪詢要求,並且您也擁有更多的控制權。例如:要隨時停止時間間隔,請確保存儲了setInterval的返回值,如下所示:

var guid = setInterval(function(){console.log("running");},1000) ; 
//Your console will output "running" every second after above command! 

clearInterval(guid) 
//calling the above will stop the interval; no more console.logs! 
+0

我不同意setInterval通過遞歸setTimeout。 setTimeout應該在一個if中,以防止它在需要停止時被再次調用。 https://zetafleet.com/blog/2010/04/why-i-consider-setinterval-to-be-harmful.html – LocalPCGuy