2017-07-17 41 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 

} 
相关问题