js实现轮询
轮询的基本概念
轮询(Polling)是一种客户端定期向服务器发送请求以获取最新数据的技术。适用于实时性要求不高或无法使用WebSocket等长连接的场景。
使用 setInterval 实现基础轮询
通过 setInterval 定时发起请求,适合简单场景:
function pollServer() {
fetch('/api/data')
.then(response => response.json())
.then(data => console.log('Data:', data))
.catch(error => console.error('Polling error:', error));
}
const intervalId = setInterval(pollServer, 5000); // 每5秒轮询一次
// 停止轮询
// clearInterval(intervalId);
使用 setTimeout 实现递归轮询
更灵活的递归方式,可动态调整间隔或根据条件停止:
function pollServer() {
fetch('/api/data')
.then(response => response.json())
.then(data => {
console.log('Data:', data);
if (data.needsUpdate) {
setTimeout(pollServer, 1000); // 数据需要更新时加快轮询
} else {
setTimeout(pollServer, 5000); // 否则恢复默认间隔
}
})
.catch(error => {
console.error('Polling error:', error);
setTimeout(pollServer, 10000); // 出错时延长间隔
});
}
pollServer(); // 启动首次轮询
带退避策略的轮询
网络异常时采用指数退避(Exponential Backoff)减少请求压力:
let retryCount = 0;
const MAX_RETRIES = 5;
const BASE_DELAY = 1000;
function pollServerWithBackoff() {
fetch('/api/data')
.then(response => {
if (!response.ok) throw new Error('Server error');
return response.json();
})
.then(data => {
retryCount = 0; // 重置重试计数
console.log('Data:', data);
setTimeout(pollServerWithBackoff, 5000);
})
.catch(error => {
if (retryCount < MAX_RETRIES) {
const delay = BASE_DELAY * Math.pow(2, retryCount);
retryCount++;
console.warn(`Retrying in ${delay}ms...`);
setTimeout(pollServerWithBackoff, delay);
} else {
console.error('Max retries reached');
}
});
}
pollServerWithBackoff();
结合 AbortController 控制轮询终止
通过 AbortController 实现请求取消,避免内存泄漏:

const abortController = new AbortController();
function controlledPolling() {
fetch('/api/data', { signal: abortController.signal })
.then(response => response.json())
.then(data => {
console.log('Data:', data);
setTimeout(controlledPolling, 3000);
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('Polling stopped');
} else {
console.error('Error:', error);
setTimeout(controlledPolling, 3000);
}
});
}
controlledPolling();
// 终止轮询
// abortController.abort();
注意事项
- 性能影响:高频轮询会增加服务器负载,需合理设置间隔时间。
- 竞态条件:确保前一次请求完成后再发起下一次请求,避免响应顺序错乱。
- 替代方案:对于高实时性需求,建议考虑WebSocket或Server-Sent Events(SSE)。






