在微信小程序中,有时候需要定时器,有时候关闭了页面,而定时器却在一直运行。我是这样解决的。
Page({
data: {
loading: ''
},
onShow: function() {
let playactive = this.data.playactive;
let player = this.data.player;
let suspend = this.data.suspend;
let $id = this.data.$id;
let that = this;
let socket;
let loading = this.data.loading;
that.setData({
loading: setInterval(function() {
socket = app.globalData.socket;
for (let i in socket) {
if (socket[i].DevId == $id) {
that.setData({
playactive: false
})
if (socket[i].openOrClose == 1) {
that.setData({
openOrClose: true
})
} else {
that.setData({
openOrClose: false
})
}
if (socket[i].playType == 1) {
that.setData({
player: true,
suspend: false
})
} else {
that.setData({
player: false,
suspend: true
})
}
if (socket[i].brightness) {
that.setData({
sliderValue: socket[i].brightness
})
}
}
}
}, 2000)
})
},
//************************** 页面卸载 ********/
onUnload: function() {
let loading = this.data.loading;
let that = this;
clearInterval(loading)
}
}
当页面卸载的时候清空定时器,当然也可以用onHide函数来清空定时器。
热门工具 换一换