利用当前时间进行倒计时

考试过程过程中,会有时间倒计时,当时间为零时,试卷要自动交卷,我开始的思路是把时间转成秒,之后通过setTimeout进行倒计时,

payCountdown(cm) {
//cm为秒钟
    let _this = this;
    if (cm >= 0 ) {
      this.hour = Math.floor((cm / 1000 / 60 / 60) % 24);
      this.hour =
        this.hour.toString().length == 1 ? "0" + this.hour : this.hour;
      this.minute = Math.floor((cm / 1000 / 60) % 60);
      this.minute =
        this.minute.toString().length == 1
          ? "0" + this.minute
          : this.minute;
      this.seconds = Math.floor((cm / 1000) % 60);
      this.seconds =
        this.seconds.toString().length == 1
          ? "0" + this.seconds
          : this.seconds;
      let _msThis = this;
       //每过一秒就减一秒,进行倒计时
      setTimeout(function () {
        cm -= 1000;
        _msThis.payCountdown(cm);
      }, 1000);
    }else {
      _this.timeOver();
    }
},

但是上边的方法有弊端,当浏览器不在该页面的时候,则会出现时间变慢,时间倒计时不对。

所以我就想着利用当前时间来进行倒计时,先让当前时间加上考试时间,之后用得到的时间减去当前时间。即使浏览器不在该页面,当回到这个页面,当前时间是变化的,所以倒计时的时间就是对的。

    mounted() {
      var time = new Date()//获得当前时间
      var b = this.countdownTime //考试时间分钟
      time.setMinutes(time.getMinutes() + b, time.getSeconds(), 0)//当前时间加上考试时间
      this.timeDown(time)
    },

//倒计时方法
timeDown(cm) {
    const time = new Date();
    //用得到的时间,减去当前时间
    const cha = cm - time;
    if(cha > 0) {
      this.hour = Math.floor((cha / 1000 / 60 / 60) % 24);
      this.hour =
        this.hour.toString().length == 1 ? "0" + this.hour : this.hour;
      this.minute = Math.floor((cha / 1000 / 60) % 60);
      this.minute =
        this.minute.toString().length == 1
          ? "0" + this.minute
          : this.minute;
      this.seconds = Math.floor((cha / 1000) % 60);
      this.seconds =
        this.seconds.toString().length == 1
          ? "0" + this.seconds
          : this.seconds;
      setTimeout( ()=> {    
        //每隔一秒就调用一次
        this.timeDown(cm);
      }, 1000);
    }else {
      this.timeOver()
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值