js轮询实现
轮询的基本概念
轮询是一种客户端定期向服务器发送请求以获取最新数据的技术。适用于需要实时更新但无需高频率的场景,如聊天应用、实时数据监控等。
简单轮询实现
使用 setInterval 定时发送请求:
function pollServer() {
fetch('/api/data')
.then(response => response.json())
.then(data => {
console.log('更新数据:', data);
})
.catch(error => {
console.error('轮询错误:', error);
});
}
// 每5秒轮询一次
const pollInterval = setInterval(pollServer, 5000);
// 停止轮询
// clearInterval(pollInterval);
带延迟的轮询
根据服务器响应动态调整下次轮询时间:
function delayedPoll(delay) {
setTimeout(() => {
fetch('/api/data')
.then(response => response.json())
.then(data => {
console.log('更新数据:', data);
delayedPoll(data.nextPollDelay || 3000); // 使用服务器建议的延迟
})
.catch(() => {
delayedPoll(10000); // 出错时延长等待
});
}, delay);
}
// 初始启动
delayedPoll(0);
带退避策略的轮询
网络异常时采用指数退避算法:
let retryCount = 0;
const MAX_RETRIES = 5;
const BASE_DELAY = 1000;
function smartPoll() {
fetch('/api/data')
.then(response => {
if (!response.ok) throw new Error('请求失败');
return response.json();
})
.then(data => {
retryCount = 0; // 成功时重置计数器
console.log('数据更新:', data);
setTimeout(smartPoll, 2000); // 正常轮询间隔
})
.catch(error => {
retryCount++;
if (retryCount > MAX_RETRIES) {
console.error('达到最大重试次数');
return;
}
const delay = Math.min(BASE_DELAY * Math.pow(2, retryCount), 30000);
console.warn(`请求失败,${delay}ms后重试`);
setTimeout(smartPoll, delay);
});
}
smartPoll();
轮询优化建议
- 添加请求取消逻辑,防止组件卸载时继续请求
- 考虑使用
AbortController中止正在进行的请求 - 对于敏感数据,确保请求包含认证令牌
- 服务端应设置适当的缓存控制头
替代方案比较
当需要更高实时性时,可考虑以下技术:

- WebSocket:持久连接,适合高频双向通信
- Server-Sent Events (SSE):服务器推送的单向通信
- Long Polling:服务器保持连接直到有数据更新






