微信小程序中清除定时器

在微信小程序的开发过程中,经常会遇到使用倒计时的情况,但是小程序的页面跳转经常会遇到跳转的下一个页面后,前一个页面的倒计时还在运行。

这时候需要我们在关闭或者离开当前页面的时候清除掉当前的倒计时,但是传统的方式在小程序中无法使用,在小程序中我采用的是赋值然后清除的方法。

传统的方式:

var myVar = setInterval(function(){ myTimer() }, 1000);
 
function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}
 
function myStopFunction() {
    clearInterval(myVar);
}

在小程序中:

Page{
    data={
        myTime:null,
    }
    onUnload () {
     clearInterval(this.myTime);
    }
    _formatSeconds () {//倒计时初始化;
      let i = 0, that = this ,orignalTime = parseInt(this.timeout)
      clearInterval(this.myTime);
      this.myTime = setInterval(() => {
        let theTime = parseInt(that.timeout), // 秒let
          theTime1 = 0, // 分let
          theTime2 = 0, // 小时
          theTime3 = 0,//天
          result
        theTime = theTime - i
        orignalTime = theTime        
        if (theTime > 60) {
          theTime1 = parseInt(theTime / 60)
          theTime = parseInt(theTime % 60)
          if (theTime1 >= 60) {
            theTime2 = parseInt(theTime1 / 60)
            theTime1 = parseInt(theTime1 % 60)
            if (theTime2 >= 24) {
              theTime3 = parseInt(theTime2 / 24)
              theTime2 = parseInt(theTime2 % 24)
              theTime1 = parseInt(theTime1 % (60 * 24))
            }
          }
        }
        result = ('00' + theTime).substr(-2)//秒
        if (theTime1 > 0) {
          result = `${('00' + theTime1).substr(-2)}:${result}`//秒+分
        } else {
          result = `00:${result}`
        }
        if (theTime2 > 0) {//秒+分+小时
          result = `${('00' + theTime2).substr(-2)}:${result}`
        } else {
          result = `00:${result}`
        }

        if (theTime3 > 0) {//秒+分+小时+天数
          result = `${('00' + theTime3).substr(-2) + '天'}:${result}`
        } else {
          result = `${result}`
        }
        if (orignalTime <= 0) {
          that.initData(this.productId, this.skuId)
        }
        i++
        that.timeText = result
        that.$apply()
      }, 1000);  
      this.$apply()    
    }
}

在函数内部通过已经定义的变量将倒计时函数赋给变量,然后通过onUnload函数清理,来实现清除倒计时的目的

注意,某些需求下,不仅要在onUnload中清除倒计时,在onHide函数中也需要清除,要根据具体需求来实现。

注:以上代码是在wepy的框架中写作的,如果在小程序原生代码中使用,需要做适当修改

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值