vue封装带天数的倒计时

vue封装带天数的倒计时,第1张

一、实现方式

此倒计时主要是使用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重复调用方法,然后获取当前时间,记录误差毫秒进行调用

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1322956.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存