vue实现每隔3s请求一次接口,返回成功则停止请求
每隔3s查询一次接口(优化版)
·
项目中有时候会遇到一个接口返回数据时间过长,需要轮询请求,直到返回成功则停止请求的需求吧!
下面教大家一个性能较好的轮询请求方式
<template> </template>
<script>
export default {
data () {
return {
timer: null,
startTime: 0 // 初始开始请求时间
}
},
methods: {
// 开始准备轮询
handlerData () {
this.startTime = new Date().getTime() // 获取触发轮询时的时间
this.inquireData() // 调用轮询接口,开始进行轮询
},
inquireData () {
const reload = () => {
clearTimeout(this.timer) // 清除定时器
// 超过30分钟则停止轮询
if (new Date().getTime() - this.startTime > 30 * 60 * 1000) {
clearTimeout(this.timer)
return
}
// 3s一次, 轮询中
this.timer = setTimeout(() => {
this.inquireData() // 调用轮询
}, 3000)
}
getInquireData()
.then(res => {
if (res && res.code === '200') {
// 需要查询的接口返回成功了,做相应的处理
} else {
// 没成功,调用轮询
reload()
}
})
.catch(err => {
// 请求错误,也继续轮询
reload()
})
}
},
beforeDestroy () {
clearTimeout(this.timer)
}
}
</script>
<style></style>
这样写的话,每次轮询都会在接口请求回来以后再进行每隔3秒的查询,不会在接口未请求回来,就进行查询,同时性能上也会更好,也可以防止接口报错,查询停止等情况
如果大家有更好的意见,也欢迎指出更正哦~
更多推荐
已为社区贡献1条内容
所有评论(0)