2017-07-17 12 views
2

我有一個setInterval函數,它顯示我網站上事件的剩餘時間。但倒計時與第二秒的實際滴答不同。Javascript:知道實際秒數是否打勾?

我的代碼使用ajax調用服務器來獲得失效日期一次,並在其成功倒計時將開始。很好,直到那裏。

var request = new XMLHttpRequest(); 
request.open('GET', 'https://my-website/service.php', true); 
request.onload = function() { 
    if (request.status >= 200 && request.status < 400) { 

     date = request.responseText; 
     timer = setInterval(showRemaining, 1000);//start the countdown 

    } else { 
     // We reached our target server, but it returned an error 
    } 
}; 

但當setInterval被調用的時候需要在同步與第二的實際全球打勾。

(我希望我是有意義的。我的意思是調用需要保持同步,每次在第二遍你的電腦或手機上的時鐘!)

我怎樣才能做到這一點?提前致謝!

+1

你需要做一個初步'setTimeout'當前MS和MS旁邊(即'1000-(新的Date()之間的差異getMilliseconds() )'),然後啓動'setInterval'請注意,setTimeout有一個最小值,所以如果它小於該值到下一秒,請添加1000. –

+0

https://stackoverflow.com/a/9647221/2181514 –

+0

如果PC /手機的時鐘是不同的,就像未來的一個星期?這裏有一些建議如何找到你的服務器時鐘和本地時鐘之間的偏移量https://stackoverflow.com/questions/1638337/the-best-way-to-synchronize-client-side-javascript-clock-with-server -date –

回答

2

你需要做的初始setTimeout與當前的MS和下一個MS,即區別:

1000-(new Date().getMilliseconds())) 

然後你可以啓動setInterval

請注意setTimeout/setInterval有一個最小值(一般認爲是10ms),所以如果它小於那個值到下一秒,就加1000.

另請注意,setTimeout/setInterval不是100%準確的,但是對於最近的秒鐘可能就足夠了。

這使你的成功代碼:

date = request.responseText; 

var t = 1000-(new Date().getMilliseconds()); 
if (t < 15) t+=1000; 

setTimeout(function() { 
    timer = setInterval(showRemaining, 1000);//start the countdown 
}, t)); 
+0

這是正確的,因爲'setInterval'似乎沒有漂移 - 它看起來像[它糾正自己](https://stackoverflow.com/questions/985670/will-setinterval-drift)。我也學到了一些東西:) – MySidesTheyAreGone

0

作爲@ freedomn -m在評論中建議,1000-(new Date().getMilliseconds())是我正在尋找的關鍵代碼 - 當前ms和下一個ms之間的差異。所以,我的代碼是現在的工作,它看起來像這樣:

if (request.status >= 200 && request.status < 400) { 

    date = request.responseText; 
    setTimeout(function() { 
     timer = setInterval(showRemaining, 1000);//start the countdown 
    }, 1000-(new Date().getMilliseconds()));//to make the calls in sync with actual tick of the second 

} 
相關問題