setTimeout 與 setInterval 是 JavaScript 非同步排程的基石。雖然 API 簡單,但「setTimeout 遞迴模擬 setInterval」、「事件循環排程延遲」、「this 綁定丟失」、「清除時機」等細節常成 Bug 溫床。本文系統梳理兩者差異、常見陷阱與現代替代方案。
| 方法 | 簽名 | 行為 | 返回值 |
|---|---|---|---|
setTimeout | (callback, delay, ...args) | 延遲 delay ms 後執行一次 | timerId (Number) |
clearTimeout | (timerId) | 取消待執行的 timeout | - |
setInterval | (callback, delay, ...args) | 每隔 delay ms 重複執行 | timerId (Number) |
clearInterval | (timerId) | 取消週期性執行 | - |
// setTimeout:單次,延遲後執行
setTimeout(() => console.log('一次'), 1000);
// setInterval:週期性,盡量按間隔觸發
setInterval(() => console.log('重複'), 1000);
// 模擬 interval(推薦用於不固定間隔、需動態調整)
function recursiveTimeout(fn, delay) {
fn();
setTimeout(() => recursiveTimeout(fn, delay), delay);
}
// 關鍵差異:
// setInterval:固定「啟動時間點」間隔(若回調慢,實際間隔變長)
// 遞迴 timeout:固定「結束到下次啟動」間隔(保證喘息時間)
const obj = {
value: 42,
log: function() { console.log(this.value); }
};
setTimeout(obj.log, 1000); // undefined (this 指向 window/global)
// 修正方法:
setTimeout(() => obj.log(), 1000); // 箭頭函數捕獲 this
setTimeout(obj.log.bind(obj), 1000); // bind 綁定
setTimeout(function() { obj.log(); }, 1000); // 匿名函數包裹
// ❌ 錯誤:全部輸出 3
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// ✅ 修正 1:let 區塊作用域 (ES6)
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0, 1, 2
}
// ✅ 修正 2:IIFE 捕獲當前值
for (var i = 0; i < 3; i++) {
((i) => setTimeout(() => console.log(i), 100))(i);
}
function countdown(seconds, onTick, onEnd) {
let remaining = seconds;
const timerId = setInterval(() => {
onTick(remaining);
if (--remaining < 0) {
clearInterval(timerId);
onEnd();
}
}, 1000);
return timerId; // 可供外部提前清除
}
// 使用
const timer = countdown(10,
(sec) => console.log(`剩餘 ${sec} 秒`),
() => console.log('時間到!')
);
// 10 秒前可取消
// clearInterval(timer);
function animate(duration, onFrame, onComplete) {
const start = performance.now();
function tick(now) {
const progress = Math.min((now - start) / duration, 1);
onFrame(progress);
if (progress < 1) requestAnimationFrame(tick);
else onComplete();
}
requestAnimationFrame(tick);
}
// worker.js
setInterval(() => postMessage('tick'), 1000);
// main.js
const worker = new Worker('worker.js');
worker.onmessage = e => console.log(e.data);
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function demo() {
console.log('開始');
await delay(1000);
console.log('1秒後');
await delay(500);
console.log('再0.5秒後');
}
useEffect cleanup、Vue onUnmounted)必須清除timerId 於狀態/Ref,避免閉包捕獲舊值clearTimeout/clearInterval 對應正確類型useInterval、useTimeout Hook 統一管理| 場景 | 推薦 API | 理由 |
|---|---|---|
| 單次延遲執行 | setTimeout / delay() Promise | 語意明確 |
| 固定間隔輪詢 | setInterval | 簡單、瀏覽器優化 |
| 需動態間隔/喘息時間 | 遞迴 setTimeout | 間隔可控 |
| 高效能動畫 | requestAnimationFrame | 對齊螢幕重繪 |
| 耗時計算 | Web Worker | 不阻塞主執行緒 |
理解定時器在事件循環中的排程行為,是寫出高效能、無 Bug 非同步代碼的關鍵。