vue封装带天数的倒计时

6 篇文章 0 订阅

一、实现方式

此倒计时主要是使用setInterval方法来实现的,注意使用的时候倒计时结束要清空,否则会导致内存泄漏

二、使用步骤

1.data部分

代码如下(示例):

// 定义一个对象保存倒计时的数字
resultTimer: {
     day: 0,
     hour: 0,
     minute: 0,
     second: 0
 },

2.methods部分

代码如下(示例):

startCountDown (endTime,startTime = Date.now()) {
      let timerInterval = null
      // 这里是结束时间减去开始时间,注意如果没有毫秒数,要把后面的÷1000【/1000】去掉
      const surplusTime = ((endTime - startTime) / 1000 ).toFixed(0)
      // 进入方法的时候清空倒计时,防止重复调用
      clearInterval(timerInterval)
      if (surplusTime > 0) {
        const day = Math.floor(surplusTime / (60 * 60 * 24))
        const hour = Math.floor(surplusTime / (60 * 60) % 24)
        const minute = Math.floor(surplusTime / 60 % 60)
        const second = Math.floor(surplusTime % 60)
        this.resultTimer.day = day
        this.resultTimer.hour = hour > 10 ? hour : '0' + hour
        this.resultTimer.minute = minute > 10 ? minute : '0' + minute
        this.resultTimer.second = second > 10 ? second : '0' + second
        timerInterval = setInterval(() => {
          --this.resultTimer.second
          if (this.resultTimer.second < 0) {
            this.resultTimer.second = 59
            --this.resultTimer.minute
            if (this.resultTimer.minute < 0) {
              this.resultTimer.minute = 59
              --this.resultTimer.hour
              if (this.resultTimer.hour < 0) {
                --this.resultTimer.day
                if (this.resultTimer.day < 0) {
                  // 这里是倒计时结束之后调用方法的地方 可以处理自己的方法
                  clearInterval(timerInterval)
                }
              } else if (this.resultTimer.hour < 10) {
                // 小于10在前面追加0
                this.resultTimer.hour = `0${this.resultTimer.hour}`
              }
            } else if (this.resultTimer.minute < 10) {
              // 小于10在前面追加0
              this.resultTimer.minute = `0${this.resultTimer.minute}`
            }
          } else if (this.resultTimer.second < 10) {
            // 小于10在前面追加0
            this.resultTimer.second = `0${this.resultTimer.second}`
          }
        }, 1000)
      }
    },

总结

这里就是简单的运用setInterval方法来实现倒计时,当然因为js是单线程的,如果还有其他方法阻塞,也有可能会造成倒计时不准确。可以用setTimeout重复调用方法,然后获取当前时间,记录误差毫秒进行调用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值