减少倒计时误差

     倒计时若直接用  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;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值