Vue中使用setTimeout实现轮询操作

解决问题:

1.  使用setInterval,网络慢的情况下,前一条请求未返回结果,后一条请求定时发送了;

2. 请求报错,停止轮询请求;

3. 轮询获取表格数据,若新建数据,调用几次刷新表格,创建几个timer;

4.  网速慢的情况下,轮询结果未返回时,切换路由,timer清除不掉。

实现方案:

export default{
    ...   // 其他定义
    data() {
        timer: null,
        isCurrentRoute: true,  // 解决:当轮询未返回结果时,切换路由后,timer清除不掉问题
    },
    created() {
        this.getTableData();
    }
    methods: {
        getTableData() {
            this.$http.GetTableData().then(res => {    // 发送后台请求
                if (res) {
                   if (this.isCurrentRoute) {
                        this.timer = setTimeout(async () => {
                            await (this.timer && clearTimeout(this.timer));
                            await this.getTableData();
                        }, 5000)
                    } 
                    ...   // 其他操作
                } else {
                    clearTimerout(this.timer);
                }
                
            })  
        } 
    },
    beforeDestroy() {
        this.isCurrentRoute= false;
        clearTimerout(this.timer);
        this.timer = null;
    }
}

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值