js 轮询实现
轮询的基本概念
轮询(Polling)是一种客户端定期向服务器发送请求以获取最新数据的机制。适用于实时性要求不高的场景,如检查状态更新、数据同步等。
简单定时轮询
通过 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 maxRetry = 5;
const baseDelay = 1000;
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 >= maxRetry) {
console.error('达到最大重试次数');
return;
}
const delay = baseDelay * Math.pow(2, retryCount); // 指数退避
console.warn(`请求失败,${delay}ms后重试...`);
setTimeout(pollWithBackoff, delay);
});
}
pollWithBackoff();
长轮询(Long Polling)
服务器在有数据时才响应,减少无效请求:
function longPoll() {
fetch('https://api.example.com/long-poll')
.then(response => {
if (response.status === 204) {
// 无数据时立即重试
longPoll();
} else {
return response.json().then(data => {
console.log('收到数据:', data);
longPoll(); // 处理完成后继续下一次轮询
});
}
})
.catch(error => {
console.error('长轮询错误:', error);
setTimeout(longPoll, 5000); // 错误时延迟重试
});
}
longPoll();
终止轮询的条件
通过标志位或外部事件停止轮询:
let isPollingActive = true;
function conditionalPoll() {
if (!isPollingActive) return;
fetch('https://api.example.com/conditional')
.then(response => response.json())
.then(data => {
console.log('当前数据:', data);
if (data.status === 'COMPLETED') {
isPollingActive = false; // 满足条件时停止
} else {
setTimeout(conditionalPoll, 3000);
}
});
}
conditionalPoll();
// 通过按钮点击停止
document.getElementById('stopButton').addEventListener('click', () => {
isPollingActive = false;
});
注意事项
- 性能影响:高频轮询会增加服务器负载,需合理设置间隔时间。
- 错误处理:网络波动或服务异常时需实现重试机制。
- 替代方案:对于高实时性需求,建议考虑 WebSocket 或 Server-Sent Events(SSE)。






