setTimeout 與 setInterval 是 JS 兩大計時器 API,看似相似但行為本質不同。本文深入解析差異、常見陷阱、現代替代方案。
| 特性 | setTimeout | setInterval |
|---|---|---|
| 執行次數 | 一次 | 重複執行 |
| 時間基準 | 延遲指定毫秒後執行 | 每隔指定毫秒執行一次 |
| 回傳值 | Timer ID(可 clearTimeout) | Timer ID(可 clearInterval) |
| 執行緒阻塞影響 | 延遲執行,不影響間隔 | 若回調執行時間 > 間隔,會堆疊/丟幀 |
| 適用場景 | 延遲執行、去抖動、一次性任務 | 輪詢、動畫循環、定期同步 |
// setTimeout
const timeoutId = setTimeout(callback, delayMs, ...args);
clearTimeout(timeoutId);
// setInterval
const intervalId = setInterval(callback, intervalMs, ...args);
clearInterval(intervalId);
// 傳遞參數(現代瀏覽器支援第三參數起)
setTimeout((a, b) => console.log(a + b), 1000, 1, 2); // 1 秒後輸出 3
// 危險範例:回調耗時 200ms,間隔 100ms
setInterval(() => {
heavyComputation(); // 耗時 200ms
}, 100);
// 結果:瀏覽器會嘗試追趕,導致:
// 1. 回調堆疊、記憶體暴增
// 2. 事件循環阻塞、UI 凍結
// 3. 某些瀏覽器會丟棄部分回調
function safeInterval(callback, interval) {
let timerId;
function tick() {
const start = performance.now();
callback();
const elapsed = performance.now() - start;
// 動態調整下一次延遲,確保間隔 ≥ 設定值
const nextDelay = Math.max(0, interval - elapsed);
timerId = setTimeout(tick, nextDelay);
}
tick(); // 立即執行第一次
return {
stop: () => clearTimeout(timerId),
// 可選:動態調整間隔
setInterval: (newInterval) => { interval = newInterval; }
};
}
// 使用
const poller = safeInterval(() => {
fetch('/api/status').then(r => r.json()).then(updateUI);
}, 5000);
// 隨時停止
poller.stop();
// 防抖:事件停止觸發 delay 後才執行
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// 節流:固定間隔執行一次
function throttle(fn, interval) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= interval) {
last = now;
fn.apply(this, args);
}
};
}
// 使用
window.addEventListener('resize', debounce(() => {
console.log('視窗大小變更完成');
}, 300));
window.addEventListener('scroll', throttle(() => {
console.log('滾動中...');
}, 100));
function animate() {
// 更新動畫狀態
updatePhysics();
render();
// 瀏覽器決定下一幀最佳時機(通常 16.67ms)
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
// 將耗時操作推到下一個事件循環
function processLargeArray(arr) {
const chunk = arr.splice(0, 1000);
chunk.forEach(heavyProcess);
if (arr.length > 0) {
setTimeout(() => processLargeArray(arr), 0); // 讓 UI 有機會回應
}
}
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ type: 'START', data: largeDataset });
worker.onmessage = e => console.log('結果:', e.data);
// worker.js
self.onmessage = e => {
const result = heavyComputation(e.data.data);
self.postMessage({ type: 'RESULT', data: result });
};
performance.now() 測量高精度時間class TimerManager {
constructor() {
this.timers = new Map();
}
setTimeout(key, fn, delay) {
this.clear(key);
this.timers.set(key, setTimeout(fn, delay));
}
setInterval(key, fn, interval) {
this.clear(key);
this.timers.set(key, setInterval(fn, interval));
}
clear(key) {
const id = this.timers.get(key);
if (id) {
clearTimeout(id); // clearTimeout/clearInterval 通用
this.timers.delete(key);
}
}
clearAll() {
this.timers.forEach(id => clearTimeout(id));
this.timers.clear();
}
}
// 元件銷毀時自動清理
componentWillUnmount() {
this.timerManager.clearAll();
}
setTimeout:一次性延遲執行,安全可控setInterval:固定間隔重複,**避免用於耗時回調**