vue 方法中使用了setInterval定时器,离开页面之后仍然在执行,想问怎么解决

这是methods方法里使用到的定时器

 async verScheme(index,row){
        var uuid =  this.getUuid();
        try {
          let ret = await this.$Api.OperationAccess.SystemAccess.Verification({
            id: row.id,
            uuid : uuid,
          })
           this.dialogFormVisible1 = true;
            this.interval =setInterval(()=> {
              this.log(uuid);
            },1000);
        }catch ( ret ){
          this.$message.error( ret.msg ? ret.msg : "校验出错 : " + ret )
        }
      },

这是使用beforeDestory()

created(){
      this.Init();
      this.timer = this.interval;
    },

    beforeDestroy() {
      if (this.timer) { //如果定时器还在运行 或者直接关闭,不用判断
        clearInterval(this.timer); //关闭
      }
    },


阅读 10.5k
4 个回答

你定时器的引用保存的不对

你this.interval 返回正确的timer了吗

可以试试requireanimationframe

针对你这个写法的一个见解
  • 既然你的定时器已经用一个interval存储起来了,为什么还要在created周期再将其保存到timer上去
  • 你在created周期执行init函数,你能保证这个函数执行完才会去执行下面的将interval赋值给timer么?若是无法保证,那么这个timer保存的是什么你应该就知道了
你那个写法比较麻烦,推荐这么一个写法,都不用保存到实例中,节省内存,而且连beforDestory周期都不用再写代码在里面
//这里直接写定时器那部分
let timer = setInterval(() => {
    //代码省略
}, 1000)
//这里的this指向vue实例
this.$once('hook:beforeDestory', function() {
    clearInterval(timer)
})
推荐问题