vue项目中 正确的使用轮询setInterval 请求接口

1.在data声明 定时器为null; 

 注意 timer其实是个数字,代表着哪一个定时器。

  data() {
    return {// 轮循定时器
      timer: null
}

2.创建轮循器   

注意:先判断是否存在已存在的定时器,有的话 关闭轮询,再重新生成

 // 开启轮询  如果存在则先销毁定时器后重新开启
    createSetInterval(ids) {
      this.stopSetInterval()
      let _this = this
      this.timer = setInterval(() => {
        _this.checkListArrayPayState(ids)
      }, 5000)
    },
    // 关闭轮询
    stopSetInterval() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }

3.关闭轮询器

注意:当页面离开的时候 定时器还是会存在在浏览器中,会继续不断请求接口 

所以不仅要手动关闭轮询,也要在vue的销毁生命周期里 再次检查并关闭轮询

 // 关闭轮询
    stopSetInterval() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }
// 离开页面销毁轮询器
  destroyed() {
    this.stopSetInterval()
  },

 

posted @ 2021-06-24 17:25  呆呆的射手座  阅读(4234)  评论(0)    收藏  举报