js倒计时的2种方法

第一种,简单时长倒计时

data() {
    return {
      timer: null,
      m: 0,
      s: 0,
      time: null,
    }
  },

created() {
    this.resetTime(125); //倒计时125S,根据自己的时长确定
 },


methods: {
    //单纯分钟和秒倒计时
    resetTime(time){
      this.m = Math.floor(time / 60);
      this.m = this.m < 10 ? `0${this.m}` : this.m;
      console.log(‘this.m--‘,this.m);
      this.s = Math.floor(time % 60);
      this.timer = setInterval(this.countDown,1000);
    },
    countDown(){
      this.s--;
      this.s < 10 && (this.s = ‘0‘ + this.s);
      // this.s = this.s < 10 ? `0${this.s}` : this.s;
      if(this.s.length >= 3){
        this.s = 59;
        this.m = `0${(Number(this.m)-1)}`;
      }
      if(this.m.length >= 3){
        this.m=‘00‘;
        this.s=‘00‘;
        clearInterval(this.timer);
      }
      this.time = `${this.m}分钟${this.s}秒`;
      console.log(this.m+"分钟"+this.s+"秒");
    },
}

 

第二种,根据后端返回的时间戳,与当前时间进去比较,进行倒计时 

data() {
    return {
     timer: null,
      time: null,
    }
  },

created() {
     this.timer = setInterval(this.countTime,1000);
 },

methods: {
    countTime() {
      //获取当前时间
      let date = new Date();
      let now = date.getTime();
      //设置截止时间
      let str="2021/3/15 00:00:00";
      let endDate = new Date(str);
      let end = endDate.getTime();
      //时间差
      let leftTime = end - now;
      //定义变量 d,h,m,s保存倒计时的时间
      let d,h,m,s;
      if (leftTime >= 0) {
        d = Math.floor(leftTime/1000/60/60/24);
        h = Math.floor(leftTime/1000/60/60%24);
        m = Math.floor(leftTime/1000/60%60);
        s = Math.floor(leftTime/1000%60);
      }else {
     clearInterval(this.timer); //为负数时清掉定时器
    }
//递归每秒调用countTime方法,显示动态时间效果
      this.time = `${m}分${s}秒`;
     if(m == 0 && s == 0) {
      clearInterval(this.timer); //时间倒计完清掉计时器,并且跳转,这里根据自己的需求写就好了
      this.$app.$redirect(‘/register/invallid‘,true);
     }

    },
}

 参照: https://www.cnblogs.com/heizai002/p/6862418.html

js倒计时的2种方法

上一篇:mysql字符长度,字节长度查询


下一篇:mysql事务的实现原理