微信小程序中清除定時器

在微信小程序的開發過程中,經常會遇到使用倒計時的情況,但是小程序的頁面跳轉經常會遇到跳轉的下一個頁面後,前一個頁面的倒計時還在運行。

這時候需要我們在關閉或者離開當前頁面的時候清除掉當前的倒計時,但是傳統的方式在小程序中無法使用,在小程序中我採用的是賦值然後清除的方法。

傳統的方式:

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的框架中寫作的,如果在小程序原生代碼中使用,需要做適當修改

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章