倒计时若直接用 setTimeout(function,ms) 函数,误差会越来越大,举个例子证明
function f(){
console.log('x');
setTimeout(f(),1000);
}
看控制台打印x的速度是否稳定保持在一秒的速度。
活动倒计时,客户手机端时间可能和服务端时间有误,所以需要求出时间差。
服务器当前时间=发请求时服务器时间+(客户端当前时间-客户端发请求时间)
countdown: function() { //倒计时
var countdown_timer;var client_current_time = new Date(); //客户端当前时间
var start_time_date = new Date(start_time); //活动开始时间
var server_time_date = new Date(server_time); //发请求时服务器端的时间
var server_current_time = server_time_date.getTime() + (client_current_time.getTime() - client_request_time.getTime()); //服务器端当前时间
coundownTime = (start_time_date.getTime() - server_current_time) / 1000; //服务器端,活动开始时间与当前时间的时间差
if(coundownTime <= 0) {
clearTimeout(countdown_timer);
this.$nextTick(function() {
this.indexDom();
})
return;
}
this.countdown_hours = time_add_zero((Math.floor(coundownTime / 60 / 60))); //时
this.countdown_min = time_add_zero(Math.floor(coundownTime / 60 % 60)); //分
this.countdown_sec = time_add_zero(Math.floor(coundownTime % 60)); //秒
countdown_timer = setTimeout(this.countdown, 500);
}
function time_add_zero(n) { //倒计时的 时/分/秒,如果小于10则在数字前面补0
if(n < 10) {
return '0' + n;
} else {
return n;
}
}