我有<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div class="col-lg-2 col-sm-2 col-md-2 col-xs-2">
<input type="checkbox" ng-model="selectedRecord.extendLiveData" > box value {{selectedRecord.extendLiveData}}
</div>
</div>
功能,显示我网站上活动的剩余时间。但倒计时与第二次倒计时不同步。
我的代码使用对服务器的ajax调用来获取一次失效日期,并且在其成功时将开始倒计时。好到那里。
setInterval
但调用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
}
};
的时间需要与第二个实际的全局价格同步。
(我希望我有道理。我的意思是,每当你的电脑或手机的时钟传递一次,电话就需要同步!)
我怎样才能实现这一目标?提前谢谢!
答案 0 :(得分:2)
您需要使用当前ms和下一个ms之间的差异制作初始 setTimeout
,即:
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));
答案 1 :(得分: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
}