用递归和定时器做一个可以控制次数和时间的轮询

最近遇到一个需求要匹配对手,然后进行对战的需求,需要使用到轮询一直请求状态,于是写了个方法,用作记录一下,首先定义数据

 data() {
    return {
      /** 定时器 */
      pollingST: null,
      /** 循环查询次数 */
      timeFlag: 0,
    }
  },

 第一次调用函数查询状态,看现在是否有房间正在匹配

    /** 点击确定回调 */
    async confirm() {
      this.timeFlag = 0
      const result = await this.getGameRoom()
      this.getPkResult(result)
    },

递归调用pollingResult函数获取状态

/** 
  * @param {Boolean} result接口返回状态
*/
pollingResult(result) {

     // 匹配成功跳转页面,匹配失败则返回,匹配时间1分钟
      if (!result) {
        console.log('匹配失败')
        this.timeFlag++
        // 大于1分钟结束
        if (this.timeFlag <= 12) {
           // 创建定时器
          this.pollingST = setTimeout( async ()=>{
            // 清除定时器
            clearTimeout(this.pollingST)
            // 调用接口函数返回结果状态
            const data = await this.getGameRoom()
            // 传入结果继续判断
            this.getPkResult(data)
          },5000)
        } else {
           console.log('匹配超时')     
        }
      } else {
        this.timeFlag = 0
        console.log('匹配成功')
      }
    },
// 接口函数
getGameRoom(){
   // 返回一个状态
}

ok 一个简单的轮询就完成了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值