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()
  },

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM