【Uniapp】Uniapp 优雅使用全局定时器
首先在全局配置文件中定义一个变量,一定是定义在全局变量中,如果定义在 data 中,则清除定时器无效,多次切换页面之后,把定时器返回的标识 ID 打印出来,你会发现 ID 已经产生了变化,导致定时器无法关闭
// 配送单数量定时器
countDeliverTimer: null,
通常情况下,都是进入页面时,初始化定时器,不断刷新消息数据等,所以我们定义在 onShow 中实现
onShow() {
if (!that.$config.countDeliverTimer) {
that.countDeliver();
that.$config.countDeliverTimer = setInterval(function () {
that.countDeliver();
}, 5000);
}
},
onHide 离开页面的时候,清空定时器
onHide() {
clearInterval(that.$config.countDeliverTimer);
that.$config.countDeliverTimer = null;
},