js 轮询实现
轮询的基本概念
轮询是一种客户端定期向服务器发送请求以检查数据更新的技术。适用于实时性要求不高的场景,但可能增加服务器负担。
简单轮询实现
使用 setInterval 定时发起请求:
function pollServer() {
fetch('/api/check-updates')
.then(response => response.json())
.then(data => {
if (data.hasUpdates) {
// 处理更新
}
});
}
const pollInterval = setInterval(pollServer, 5000); // 每5秒轮询
// 停止轮询
// clearInterval(pollInterval);
带退避策略的轮询
当无更新时逐步延长轮询间隔:
let retryDelay = 1000;
const maxDelay = 60000;
function smartPoll() {
fetch('/api/check')
.then(res => res.json())
.then(data => {
if (data.updated) {
retryDelay = 1000; // 重置延迟
// 处理数据
} else {
retryDelay = Math.min(retryDelay * 2, maxDelay);
}
setTimeout(smartPoll, retryDelay);
});
}
smartPoll(); // 启动
错误处理增强版
添加网络错误处理和重试机制:
let retryCount = 0;
const MAX_RETRIES = 3;
function robustPoll() {
fetch('/api/data')
.then(response => {
if (!response.ok) throw new Error('Server error');
return response.json();
})
.then(handleData)
.catch(error => {
if (retryCount < MAX_RETRIES) {
retryCount++;
setTimeout(robustPoll, 2000 * retryCount);
} else {
console.error('Polling failed after retries');
}
});
}
function handleData(data) {
retryCount = 0; // 成功时重置计数器
// 业务逻辑处理
setTimeout(robustPoll, 5000); // 正常轮询间隔
}
基于Promise的链式轮询
实现请求完成后再发起下一次请求的模式:

function chainPoll() {
return fetch('/api/items')
.then(res => res.json())
.then(data => {
// 处理数据
return new Promise(resolve => {
setTimeout(() => {
resolve(chainPoll());
}, 3000);
});
});
}
chainPoll(); // 启动链式调用
性能优化建议
- 对于频繁更新的数据,考虑WebSocket替代方案
- 添加请求取消逻辑(使用AbortController)
- 在页面不可见时(document.visibilityState)暂停轮询
- 服务端应设置适当的缓存控制头






