关于vue项目中clearInterval方法不起作用的问题及解决方案

940 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第12天

关于vue项目中clearInterval方法不起作用的问题及解决方案

今天在vue项目中做轮播图时,遇到了clearInterval在当前页面中正常运行,但路由跳转时不起作用的情况,我一开始是这样定义的:

//data中定义timer标识符
return {
            timer: null,
        }
//methods中
setTimer(){
            this.timer = setInterval(()=>{
                this.next();//next()是轮播图播放方法,这里不展开说明
            }
            ,3000);
        },
         
//在created生命周期函数中调用setTimer方法
created() {
      setTimeout(() => {
        this.setTimer();
      }, 3000)
    },
        
//在beforeDestoryed生命周期函数中调用clearInterval方法
beforeDestroy(){
        clearInterval(this.timer);
    },

通过setTimer和clearInterval函数调用次数来判断,路由跳转后计时器个数应该为0,但在另外一个页面中却持续报错

查阅资料后,做出如下调整:

1、调用setInterval和clearInterval方法,应写成window.setInterval和window.clearInterval形式,问题未解决

2、资料如下所写:

此外还需要注意的是,你应该避免在beforeCreate 和created 生命周期时产生全局副作用的代码,例如在其中使用setInterval 设置timer。在纯客户端(client-side only)的代码中,我们可以设置一个timer,然后在beforeDestroy 或destroyed 生命周期时将其销毁。但是,由于在SSR期间并不会调用定时器,然后在在毁灭前或摧毁了生命周期时将其销毁。销毁钩子函数,所以timer将永远保留下来。为了避免这种情况,请将副作用代码移动到beforeMount或!mounted生命周期中。

我便将clearInterval方法转移至beforeMount生命周期函数中,不过问题仍未解决

3、使用$once事件监听,在定义完定时器之后的位置来清除定时器 :

setTimer(){
            this.timer = window.setInterval(()=>{
                this.next();
            }
            ,3000);
            this.timerNum++;
            this.$once('hook:beforeDestroy', () => {
                window.clearInterval(this.timer);
            })
        },

问题解决!原理尚未明确,需往后不断进行学习

参考文章:

vue组件里定时器销毁问题 - super_素素 - 博客园 (cnblogs.com)

(129条消息) 【前端】Vue使用clearInterval()无效不起作用sunshine641的博客-CSDN博客clearinterval无效