Js轮训实现
轮询的实现方法
轮询(Polling)是一种客户端定期向服务器发送请求以获取最新数据的技术。适用于实时性要求不高的场景,实现简单但可能增加服务器负载。
使用setInterval实现基础轮询
通过setInterval定时发送请求,适合固定间隔的轮询需求。

function startPolling(url, interval) {
const poll = setInterval(async () => {
try {
const response = await fetch(url);
const data = await response.json();
console.log('Received data:', data);
} catch (error) {
console.error('Polling error:', error);
}
}, interval);
// 返回清除函数
return () => clearInterval(poll);
}
// 使用示例
const stopPolling = startPolling('/api/data', 3000);
// 需要停止时调用
// stopPolling();
使用setTimeout实现递归轮询
递归方式更灵活,可根据响应结果动态调整下次轮询时间。

function recursivePoll(url, delay) {
setTimeout(async () => {
try {
const response = await fetch(url);
const data = await response.json();
console.log('Data update:', data);
// 根据业务逻辑调整下次轮询时间
const nextDelay = data.requiresQuickUpdate ? 1000 : 3000;
recursivePoll(url, nextDelay);
} catch (error) {
console.error('Polling failed:', error);
recursivePoll(url, Math.min(delay * 2, 60000)); // 退避策略
}
}, delay);
}
// 启动轮询
recursivePoll('/api/status', 2000);
带退避策略的轮询
网络异常时采用指数退避算法,避免雪崩效应。
const MAX_DELAY = 60000;
const BASE_DELAY = 1000;
function smartPoll(url, delay = BASE_DELAY) {
fetch(url)
.then(response => {
if (!response.ok) throw new Error('Server error');
return response.json();
})
.then(data => {
console.log('New data:', data);
smartPoll(url, BASE_DELAY); // 成功时重置延迟
})
.catch(error => {
console.warn(`Retrying in ${delay}ms`, error);
const nextDelay = Math.min(delay * 2, MAX_DELAY);
setTimeout(() => smartPoll(url, nextDelay), delay);
});
}
轮询优化建议
- 条件轮询:在响应头中携带
Last-Modified或ETag,减少不必要的数据传输 - 取消机制:使用
AbortController实现请求取消 - 页面可见性:当标签页不可见时暂停轮询
// 带取消功能的实现
function cancellablePoll(url, interval) {
const controller = new AbortController();
const poll = setInterval(async () => {
try {
const response = await fetch(url, {
signal: controller.signal
});
// 处理数据...
} catch (e) {
if (e.name !== 'AbortError') {
console.error(e);
}
}
}, interval);
return () => {
clearInterval(poll);
controller.abort();
};
}
替代方案考虑
对于高实时性要求的场景,建议考虑:
- WebSocket 双向通信
- Server-Sent Events (SSE) 服务器推送
- Long Polling 长轮询技术
轮询实现应根据具体业务需求选择适当间隔和错误处理策略,平衡实时性和服务器压力。






