在微信小程序的开发过程中,经常会遇到使用倒计时的情况,但是小程序的页面跳转经常会遇到跳转的下一个页面后,前一个页面的倒计时还在运行。
这时候需要我们在关闭或者离开当前页面的时候清除掉当前的倒计时,但是传统的方式在小程序中无法使用,在小程序中我采用的是赋值然后清除的方法。
传统的方式:
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的框架中写作的,如果在小程序原生代码中使用,需要做适当修改