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

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

1
2
3
4
//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 @   张亮java  阅读(4126)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2016-05-10 struts2中的jsp值传到后台action接收的三种方法
2016-05-10 mysql时间格式化,按时间段查询的MySQL语句
2016-05-10 复选框做成单选效果
2016-05-10 SSH整合报错:org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped[......]
点击右上角即可分享
微信分享提示