小程序組件中無法清除定時器
1.把定時器設置為全局變量(保存在data里面)
2.在lifetimes-->detached里面清除定時器
lifetimes: { attached: function() { this.addInterval(); }, detached: function() { // 在組件實例被從頁面節點樹移除時執行 clearInterval(this.data.timeOut)//清除定時器 }, }, methods: { addInterval(e){ //當e==remove時,把原來的定時器刪掉 const {timeNum}=this.properties; this.setData({time:timeNum}) //設置倒計時十秒鍾 if(e!="remove"){ var timeOut=setInterval(() => { if(this.data.time==0||e=="remove") { clearInterval(timeOut); this.triggerEvent('timeEnd',{},{}) return } this.setData({time:this.data.time-1}) }, 1000); this.setData({timeOut:timeOut}) } },
