微信小程序 设置计时器(setInterval)、清除计时器(clearInterval)
1、wxml代码
<!--index.wxml--> <view class="container"> <button type='primary' style='margin-bottom:40px;' bindtap='startSetInter'>开始</button> <button type='primary' bindtap='endSetInter'>结束</button> </view>
2、js代码
将计时器赋值给 data 中的变量,这样在任何方法中都可以清除计时器
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) }, })
最新评论