小程序内使用setInterval()
来自维基鲸
小程序内使用setInterval()循环执行,退出页面时清除停止
var app = getApp();
Page({
data: {
interval:""
},
start: function () {
const that = this;
// 赋值
that.setData({
//给声明的变量interval赋值,每1000毫秒执行一次
interval: setInterval(() => {
//逻辑代码
.........
}, 1000)
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this
//开始计时器
that.start()
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
const that =this;
//结束定时器
clearInterval(that.data.interval)
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
const that =this;
//结束定时器
clearInterval(that.data.interval)
}
})
