一、wxml代碼javascript
<!--index.wxml--> <view class="container"> <button type='primary' style='margin-bottom:40px;' bindtap='startSetInter'>開始</button> <button type='primary' bindtap='endSetInter'>結束</button> </view>
二、js代碼java
將計時器賦值給 data 中的變量,這樣在任何方法中均可以清除計時器ide
Page({ data: { //存儲計時器 setInter:'', num:1, }, onLoad: function () { var that = this; }, startSetInter: function(){ var that = this; //將計時器賦值給setInter that.data.setInter = setInterval( function () { var numVal = that.data.num + 1; that.setData({ num: numVal }); console.log('setInterval==' + that.data.num); } , 2000); }, endSetInter: function(){ var that = this; //清除計時器 即清除setInter clearInterval(that.data.setInter) }, onHide: function () { }, onUnload: function () { var that =this; //清除計時器 即清除setInter clearInterval(that.data.setInter) }, })