项目中我们经常需要实现轮询接口,每隔几秒请求一次接口刷新数据
一般都会使用setInterval,但要注意单纯使用它可能导致页面卡死
原因是setInterval不会清除定时器队列,每重复执行1次都会导致定时器叠加
但是setTimeout是自带清除定时器的队列。所以可以把二者结合起来使用。

方法一

data() {
  return {
    timer: null,
  }
}

created() {
  //设置定时器,注意:只有在 created 生命周期中设置的定时器 才能在beforeDestroy 中销毁
  this.timer = window.setInterval(() => {
    setTimeout(this.pollingFunc(), 0)
  }, 1000)
}

beforeDestroy() {
  //在 beforeDestroy生命周期函数中销毁定时器
  clearInterval(this.inter);
  this.inter = null;
}

methods: {
  pollingFunc() {
    this.$http.get(api.MoSum, {
      params: { data_type: 2, task_id: this.task_id }
    })
      .then(res => {
        if (res.status === 200) {
          this.tableData = res.result.data
          this.loading = false
        }
      })
  }
}

第一种方法确实是可行的,可是存在的问题是

1、 data中需要有这个定时器的实例,感觉有点多余;
2、创建的定时器代码和销毁定时器的代码没有放在一起,通常很容易忘记去清理这个定时器,不容易维护;

方法二:直接在需要定时器的方法或者生命周期函数中声明并销毁

methods: {
  fun1(){
    const timer = setInterval(() => {
      //需要做的事情
      console.log(11111);
    }, 1000);

    // this.$once('hook:beforeDestroy',()=>{
    //   clearInterval(timer);
    //   timer = null;
    // })
    this.$on('hook:beforeDestroy', () => {
      clearInterval(times)
      this.timer = null
    })
  }
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐