倒计时在开发过程中经常会遇到,常见的如:获取验证码时需要倒计时,付款时的付款时间倒计时,下订单时的倒计时,今天就做一个简单的总结

普通的倒计时方法1.0版本

    countDown() {
        // 定义一个一秒的计时器,返回一个ID值
        const clockId = setInterval(() => { 
          // 判断剩余时间>1的情况下,时间自减1
          if (this.countNumber > 1) {
            this.countNumber -- 
          } else {
            // 剩余时间为0的情况下,清除定时器,初始化数据
            clearInterval(clockId)
            this.isCount = !this.isCount
            this.countNumber = 60
          }
        }, 1000)
      }

1.0版本的方法是大部分人容易理解的方法,易上手,但是该方法略过冗余,于是1.1版本来咯~~

升级版的倒计时方法1.1版本

    countDown(){
     const clockId = setInterval(()=>{
      // 时间先自减1,再判断是否<=0
      //(为了程序严谨,以防未知情况下出现的时间<0,所以判断条件为<=0)
      this.countNumber --
       if (this.countNumber < 0) {
        clearInterval(clockId)
        this.countNumber = 60
       }
     }, 1000)
    }
 

以上的1.1版本更轻松地实现了倒计时的功能,但是我们依然不能满足。在平时的开发过程中,倒计时的功能还会和时间的转换结合在一起,那么继续往下看拓展版吧~~

    <div class="count-tips">{{ timeCycle(countNumber) }}</div>
     countDown() {
      const clockId = setInterval(()=>{
      this.countNumber --;
      if(this.countNumber <= 0){
        clearInterval(clockId);
       }
      },1000)
     }

时间转换方法

     timeCycle(countNumber) {
      return ~~(countNumber / 60) + '分' + countNumber % 60 + '秒'
    },

实现效果如下:

count-down.png

技术总结:

1.定义计时器的之后,别忘了在满足条件后去取消定时器,不然会永久执行
2.倒计时需要在剩余时间大于0的条件下执行

标签: js倒计时

添加新评论