uni-app 中使用定时器和清除定时器

uni-app 中我们应该如何使用定时器呢?在结束后我们该如何让清除定时器? 下面我们就来分享一下吧。

1、 定义一个timer

data(){
    return{
        timer: null
    }
}

2、设置定时器

//选择适合需求的定时器
this.timer = setTimeout( () => {
    // 这里添加您的逻辑		
}, 1000)
this.timer = setInterval( () => {
    // 同上			
}, 1000)

3、清除定时器

⚠️: 这里需要注意的是我们页面中使用了定时器,在离开这个页面的时候一定要记得清除,避免出现bug。

  • 一般页面用onUnload
onUnload() {
	if(this.timer) {  
		clearTimeout(this.timer);  
		this.timer = null;  
	}  
}
  • tabbar页面用onHide
onHide() {
	if(this.timer) {  
		clearTimeout(this.timer);  
		this.timer = null;  
	}  
}
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐