uniapp轮询定时器
uniapp轮询定时器的实现方法
在uniapp中实现轮询定时器,通常有两种方式:setInterval和setTimeout递归调用。以下是具体实现方法及注意事项。
使用setInterval实现轮询
在页面或组件的onLoad或mounted生命周期中启动定时器,onUnload或beforeDestroy中清除定时器,避免内存泄漏。
export default {
data() {
return {
timer: null,
pollCount: 0
}
},
onLoad() {
this.startPolling()
},
onUnload() {
this.stopPolling()
},
methods: {
startPolling() {
this.timer = setInterval(() => {
this.pollCount++
console.log('轮询执行次数:', this.pollCount)
this.fetchData()
}, 3000) // 每3秒执行一次
},
stopPolling() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
},
fetchData() {
// 实际业务请求逻辑
uni.request({
url: 'https://example.com/api/data',
success: (res) => {
console.log('轮询获取数据:', res.data)
}
})
}
}
}
使用setTimeout实现递归轮询
通过递归调用setTimeout实现轮询,避免setInterval可能带来的执行堆叠问题。
export default {
data() {
return {
pollCount: 0
}
},
onLoad() {
this.startPolling()
},
methods: {
startPolling() {
this.fetchData()
},
fetchData() {
uni.request({
url: 'https://example.com/api/data',
success: (res) => {
console.log('轮询获取数据:', res.data)
this.pollCount++
// 递归调用,实现间隔轮询
setTimeout(() => {
this.fetchData()
}, 3000)
},
fail: (err) => {
console.error('请求失败:', err)
// 失败后仍继续轮询
setTimeout(() => {
this.fetchData()
}, 3000)
}
})
}
}
}
注意事项
轮询间隔时间需根据业务需求合理设置,避免过频请求导致服务器压力过大或客户端性能问题。
在页面卸载时务必清除定时器,防止内存泄漏。对于全局轮询逻辑,可在App.vue中管理。
网络请求建议添加超时处理和错误重试机制,提升用户体验。

对于需要精确同步的场景,可考虑使用WebSocket替代轮询方案。






