js 实现轮询
使用 setInterval 实现轮询
通过 setInterval 可以定期执行某个函数,适合简单的轮询场景。
const pollInterval = setInterval(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
if (data.ready) {
clearInterval(pollInterval);
console.log('Data ready:', data);
}
})
.catch(error => console.error('Polling error:', error));
}, 2000); // 每2秒轮询一次
使用 setTimeout 递归实现轮询
递归调用 setTimeout 可以更灵活地控制轮询间隔,避免 setInterval 的潜在问题(如请求堆积)。
function poll() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
if (data.ready) {
console.log('Data ready:', data);
} else {
setTimeout(poll, 2000); // 未就绪时,2秒后重试
}
})
.catch(error => {
console.error('Polling error:', error);
setTimeout(poll, 2000); // 错误时,2秒后重试
});
}
poll(); // 启动轮询
结合指数退避策略
指数退避可以避免频繁轮询对服务器造成压力,适合高延迟或不确定响应时间的场景。
function pollWithBackoff(initialDelay = 1000, maxDelay = 30000) {
let currentDelay = initialDelay;
function poll() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
if (data.ready) {
console.log('Data ready:', data);
} else {
currentDelay = Math.min(currentDelay * 2, maxDelay);
setTimeout(poll, currentDelay);
}
})
.catch(error => {
console.error('Polling error:', error);
currentDelay = Math.min(currentDelay * 2, maxDelay);
setTimeout(poll, currentDelay);
});
}
poll(); // 启动轮询
}
pollWithBackoff();
使用 AbortController 取消轮询
通过 AbortController 可以手动终止轮询,避免不必要的网络请求。
const abortController = new AbortController();
function poll() {
fetch('https://api.example.com/data', {
signal: abortController.signal
})
.then(response => response.json())
.then(data => {
if (data.ready) {
console.log('Data ready:', data);
} else {
setTimeout(poll, 2000);
}
})
.catch(error => {
if (error.name !== 'AbortError') {
console.error('Polling error:', error);
setTimeout(poll, 2000);
}
});
}
poll();
// 需要取消时调用
// abortController.abort();
结合 async/await 的轮询实现
使用 async/await 可以让代码更易读,适合现代 JavaScript 开发。

async function poll() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
if (data.ready) {
console.log('Data ready:', data);
} else {
await new Promise(resolve => setTimeout(resolve, 2000));
await poll(); // 递归调用
}
} catch (error) {
console.error('Polling error:', error);
await new Promise(resolve => setTimeout(resolve, 2000));
await poll(); // 递归调用
}
}
poll();






