最近遇到一个需求要匹配对手,然后进行对战的需求,需要使用到轮询一直请求状态,于是写了个方法,用作记录一下,首先定义数据
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 一个简单的轮询就完成了