核心模式:setInterval + clearInterval
// 全局定時器 ID
var refreshId = null;
function startPolling() {
// 防止重複啟動
if (refreshId) return;
refreshId = setInterval(pollTask, 1000); // 每秒輪詢
}
function pollTask() {
try {
var result = doBusinessCheck(); // 業務檢查函數
if (result === '1') { // '1' 表示未完成/繼續輪詢
return; // 保持定時器運行
}
// 成功條件:result !== '1' (如返回數據對象、true、'success' 等)
stopPolling();
handleSuccess(result);
} catch (e) {
console.error('輪詢異常:', e);
stopPolling();
handleError(e);
}
}
function stopPolling() {
if (refreshId) {
clearInterval(refreshId);
refreshId = null;
}
}
function doBusinessCheck() {
// 模擬:返回 '1' 繼續,返回數據對象表示完成
// 實際場景:AJAX 請求後端狀態接口
return '1';
}
function handleSuccess(data) {
console.log('輪詢成功,結果:', data);
// 更新 UI、跳轉頁面、觸發回調等
}
function handleError(err) {
alert('輪詢異常停止: ' + err.message);
}
進階模式:Promise + async/await 現代寫法
class Poller {
constructor(options = {}) {
this.interval = options.interval || 1000;
this.maxAttempts = options.maxAttempts || 60; // 最大嘗試次數
this.attempts = 0;
this.timerId = null;
this.abortController = new AbortController();
}
async start(checkFn, successFn, errorFn) {
this.checkFn = checkFn;
this.successFn = successFn;
this.errorFn = errorFn;
this.attempts = 0;
this._tick();
}
_tick() {
if (this.attempts >= this.maxAttempts) {
this.stop();
this.errorFn?.(new Error('輪詢超時'));
return;
}
this.attempts++;
Promise.resolve(this.checkFn())
.then(result => {
if (this._isSuccess(result)) {
this.stop();
this.successFn?.(result);
} else {
// 繼續下一輪
this.timerId = setTimeout(() => this._tick(), this.interval);
}
})
.catch(err => {
this.stop();
this.errorFn?.(err);
});
}
_isSuccess(result) {
// 自定義成功判斷邏輯
return result !== '1' && result != null;
}
stop() {
if (this.timerId) {
clearTimeout(this.timerId);
this.timerId = null;
}
}
}
// 使用
var poller = new Poller({interval: 2000, maxAttempts: 30});
poller.start(
() => fetch('/api/status').then(r => r.json()), // 檢查函數
data => console.log('完成:', data), // 成功回調
err => console.error('失敗:', err) // 失敗回調
);
關鍵最佳實踐
- 全局變量存儲 timerId:防止多次啟動、便於清理。
- 成功條件明確化:約定業務返回值語義(如
{done: true, data:...}),避免魔術字符串。
- 異常捕獲與清理:
try-catch 包裹,異常時必須 clearInterval 避免死循環。
- 最大嘗試次數/超時:防止後端故障導致無限輪詢消耗資源。
- 指數退避:
interval *= 1.5 減輕服務端壓力。
- 頁面可見性 API:
document.hidden 時暫停,顯示時恢復,節省資源。
頁面可見性優化示例
var poller = new Poller({interval: 1000});
document.addEventListener('visibilitychange', function() {
if (document.hidden) {
poller.pause();
} else {
poller.resume();
}
});
// Poller 類添加 pause/resume
pause() { this.stop(); }
resume() { if (!this.timerId) this._tick(); }