前端倒计时vue

一定要清楚定时器,,减少内存泄露
HTML渲染:

  {{hangTime.day}}{{hangTime.hour}}{{hangTime.min}}{{hangTime.second}}
data(){
return{
timer:null}

//在需要的地方调用countTime,如获取到时间差的时候

  countTime(time) {
          let _this = this;
          if (!this.timer) {
            let leftTime = time
            this.timer = setInterval(() => {
              let isOver = true
              let item = this.hangTime
              if (Number(item.hour) === 0 && Number(item.day) === 0 && Number(item.min) === 0 && Number(
                  item
                .second) === 0) {} else {
                isOver = false
                if (leftTime > 0) {
                  leftTime--;
                  // 天
                  this.hangTime.day = Math.floor(leftTime / 60 / 60 / 24)
                  // 时
                  let h = Math.floor(leftTime / 60 / 60 % 24)
                  this.hangTime.hour = h < 10 ? '0' + h : h
                  // 分
                  let m = Math.floor(leftTime / 60 % 60)
                  this.hangTime.min = m < 10 ? '0' + m : m
                  // 秒
                  let s = Math.floor(leftTime % 60)
                  this.hangTime.second = s
                } else {
                  clearInterval(this.timer);
                  this.timer = null;
                  this.hangTime.day = '00'
                  this.hangTime.hour = '00'
                  this.hangTime.min = '00'
                  this.hangTime.second = '00'
                }
              }
              if (isOver) {
                clearInterval(this.timer);
                this.timer = null;
              }
            }, 1000);
          }
        },

//一定要清楚定时器,,减少内存泄露

destroyed() {
        clearInterval(this.timer)
        this.timer = null;
      }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值