Js轮训实现
轮询的实现方法
轮询是一种通过定时向服务器发送请求来获取最新数据的技术,适用于需要实时更新的场景。以下是几种常见的实现方式:
使用setInterval实现基础轮询

function pollServer() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log('Received data:', data);
})
.catch(error => {
console.error('Polling error:', error);
});
}
const intervalId = setInterval(pollServer, 5000);
// 停止轮询
// clearInterval(intervalId);
使用setTimeout实现可控轮询

function pollServer() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log('Data update:', data);
setTimeout(pollServer, 3000); // 成功后再发起下一次请求
})
.catch(error => {
console.error('Polling failed:', error);
setTimeout(pollServer, 10000); // 失败后延长间隔
});
}
pollServer(); // 启动首次请求
带条件退出的轮询
let pollingActive = true;
function conditionalPoll() {
if (!pollingActive) return;
fetch('https://api.example.com/status')
.then(response => response.json())
.then(data => {
if (data.completed) {
console.log('Processing completed');
pollingActive = false;
} else {
setTimeout(conditionalPoll, 2000);
}
});
}
conditionalPoll();
优化建议
- 添加退避策略:遇到错误时逐步增加轮询间隔
- 设置最大重试次数防止无限循环
- 在页面不可见时暂停轮询(通过Page Visibility API)
- 考虑使用指数退避算法处理连续错误
替代方案
对于需要更高实时性的场景,建议考虑:
- WebSocket双向通信
- Server-Sent Events(SSE)服务端推送
- 长轮询(Long Polling)技术
轮询适合简单场景,但频繁请求可能导致服务器压力增大,应根据实际需求选择合适方案。






