js 实现轮询
轮询的基本概念
轮询是一种客户端定期向服务器发送请求以获取最新数据的技术,适用于需要实时更新但无法使用WebSocket或Server-Sent Events(SSE)的场景。

简单轮询实现
通过 setInterval 定时发起请求,代码示例:

function pollServer() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log('更新数据:', data))
.catch(error => console.error('请求失败:', error));
}
// 每5秒轮询一次
const pollInterval = setInterval(pollServer, 5000);
// 停止轮询
// clearInterval(pollInterval);
指数退避轮询
当服务器压力大时,可采用指数退避策略动态调整轮询间隔:
let retryCount = 0;
const maxRetries = 5;
const baseDelay = 1000; // 初始延迟1秒
function pollWithBackoff() {
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error('请求失败');
retryCount = 0; // 成功时重置重试计数
return response.json();
})
.then(data => {
console.log('数据更新:', data);
setTimeout(pollWithBackoff, baseDelay); // 正常延迟
})
.catch(error => {
retryCount++;
if (retryCount > maxRetries) {
console.error('达到最大重试次数');
return;
}
const delay = baseDelay * Math.pow(2, retryCount);
console.log(`第${retryCount}次重试,延迟${delay}ms`);
setTimeout(pollWithBackoff, delay);
});
}
pollWithBackoff();
基于Promise的轮询
结合 async/await 实现更可控的轮询逻辑:
async function pollUntilCondition(conditionFn, interval = 3000) {
while (true) {
try {
const response = await fetch('https://api.example.com/status');
const data = await response.json();
if (conditionFn(data)) {
console.log('条件满足:', data);
return data;
}
await new Promise(resolve => setTimeout(resolve, interval));
} catch (error) {
console.error('轮询异常:', error);
await new Promise(resolve => setTimeout(resolve, interval));
}
}
}
// 使用示例:检测任务是否完成
pollUntilCondition(data => data.status === 'completed');
注意事项
- 性能优化:避免高频轮询,根据业务需求合理设置间隔时间。
- 错误处理:添加网络异常和服务器错误的重试机制。
- 资源释放:在页面卸载时清除轮询(如
beforeunload事件中调用clearInterval)。






