微信小程序中清除定时器

您所在的位置:网站首页 小沙漏倒计时怎么删除 微信小程序中清除定时器

微信小程序中清除定时器

2024-06-10 03:23| 来源: 网络整理| 查看: 265

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

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

传统的方式:

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


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3