每隔10秒轮询接口

场景:
1、数据量庞大
2、每隔几秒请求一次接口刷新数据

在查询数据的时候,由于参数和数据量庞大,在查询数据库可能返回数据较慢,导致接口超时报错等,因此需要轮询的方式,每隔10秒去查询接口。

方法:setInterval、setTimeout

// 查询
search() {
    const delayTime = 60 * 1000
    let res = this.getData()
    if (res === 0) {
        // 清除定时器
        clearInterval(this.timer)
        console.log('查询成功')
    } else {
        console.log('查询超时')
        // 清除定时器
        clearInterval(this.timer)
        this.timer = setInterval(() => {
            this.search()
        }, delayTime)
    }
},
// 查询数据
getData() {}

注意:setInterval需要清除定时器队列,每重复执行1次都会导致定时器叠加,在销毁周期destroyed也要清除setInterval

评论

暂无评论