定时器
第一步:定义定时器变量(如果定时器需要在不同的函数中启动与结束,就需要定义一个全局变量)
data: {
setTime: null, //定时器
}
第二步:定义启动定时器函数
startCount : function(){
this.data.setTime= setInterval(
this.countTime, 1000);
},
第三步:定义定时器需要定时执行的函数
countTime: function () {
//TODO
}
第四步:在某事件中启动定时器,此时countTime函数就会定时执行了
myFn: function () {
this.startInter();
},
第五步:清除定时器
clearInterval(this.data.setTime)
小程序页面退出时,定时器和长连接等不会自动清除断开,所以如果页面内没有清除定时器,需要在生命周期onUnload函数中手动清除定时器。
onUnload: function () {
//结束定时器
clearInterval(this.data.setTime)
},
(在vue中切换页面也需手动在生命周期函数beforeDestroy中清除定时器)。
beforeDestroy() {
clearInterval(this.setTime)
this.set = null;
},