vue 项目中如何优雅地使用定时器

2020-11-19  本文已影响0人  杨同学a

清除时高效的方法

常规使用

this.timer = (() => {
    // 某些操作
}, 1000)复制代码

//最后在beforeDestroy()生命周期内清除定时器:
beforeDestroy() {
    clearInterval(this.timer);        
    this.timer = null;
}复制代码
const timer = setInterval(() =>{                    
    // 某些定时器操作                
}, 500);            
// 通过$once来监听定时器,在beforeDestroy钩子可以被清除。
this.$once('hook:beforeDestroy', () => {            
    clearInterval(timer);                                    
})复制代码
上一篇 下一篇

猜你喜欢

热点阅读