vue实现每隔几秒请求一次接口(轮询)

单纯使用setInterval会使页面卡死,setTimeout自带清除缓存,组合使用实现轮询可解决浏览器崩溃

//30秒调用一次fun 方法
window.setInterval(() => {
  setTimeout(fun, 0)
}, 30000)

  

如下方法:

data() {
    return {
      times: null, 
    };
  },
created() {
    this.getDataFun();
  // 实现轮询
    this.times = setInterval(() => {
      this.getDataFun();
    }, 1000 * 60);
  },
methods: {
  getDataFun() {
    //请求XXXXXX
  },

  stop() {
      clearInterval(this.timer);
      this.timer = null;
    },
} ,
destroyed() {
  //销毁 clearInterval(this.times);
   this.timer = null;
},

 接下来写一个案例:

created() {
    // 实现轮询
    this.autoGetNotHandleData();
  },

methods: {
    destroyed() {
       //销毁 
       clearInterval(this.times);   
       this.timer = null;
    },
    autoGetNotHandleData(){
      // 实现轮询
      this.times = setInterval(() => {
        if(this.dataSource && this.dataSource.length>0){
            this.onSelectChange([this.dataSource[0].businessUnitCode], [this.dataSource[0]]);
            this.destroyed()
        }
      }, 500);
      
    },
}

 

posted @ 2022-05-10 17:25  张亮java  阅读(3974)  评论(0编辑  收藏  举报