Vue清除定时器,延时器setIntederval,setTimeout的优化方案

Vue清除定时器,延时器setIntederval,setTimeout的优化方案:

两种方案清除定时器,在开发过程中经常使用方案1,建议使用方案2,

方案1:

首先定义定时器名称:

data() {            
    return {                              
        timer: null  // 定时器名称          
    }        
},

使用定时器:

this.timer = setTimeout(() => {
    // 某些操作
}, 1000)

最后在beforeDestroy()生命周期内清除定时器:

beforeDestroy() {
    clearInterval(this.timer);        
    this.timer = null;
}

方案2:

该方法是通过$once这个事件侦听器器在定义完定时器之后的位置来清除定时器。以下是代码:

const timer = setInterval(() =>{                    
    // 某些定时器操作                
}, 500);            
// 通过$once来监听定时器,在beforeDestroy钩子可以被清除。
this.$once('hook:beforeDestroy', () => {            
    clearInterval(timer);                                    
})

猜你喜欢

转载自blog.csdn.net/AN0692/article/details/108885932
今日推荐