setTimeout(fn, delay, ...args) 現代瀏覽器已原生支援傳遞參數,但舊代碼常見 setTimeout('func('+arg+')', 1000) 字串寫法(eval 風險)或 setTimeout(function(){fn(arg)}, 1000) 包裹寫法。本文系統整理各種傳參模式、閉包陷阱、循環綁定問題與最佳實踐。
// 直接傳遞額外參數給回呼函數
setTimeout((a, b, c) => console.log(a, b, c), 1000, 'x', 'y', 'z');
// 1秒後輸出: x y z
// 配合解構
setTimeout(({x, y}) => console.log(x + y), 1000, {x: 1, y: 2}); // 3
| 模式 | 程式碼 | 優缺點 |
|---|---|---|
| 箭頭函數包裹 | setTimeout(() => fn(arg), 1000) | 簡潔、保持 this、ES6+ 環境通用 |
| Function.prototype.bind | setTimeout(fn.bind(null, arg), 1000) | 語意明確、可預設 this、需建立新函數 |
| IIFE 立即執行函數 | setTimeout((a => () => fn(a))(arg), 1000) | 經典閉包捕獲、語法較繁瑣 |
| 閉包工廠函數 | const wrap = a => () => fn(a); setTimeout(wrap(arg), 1000) | 可複用、適合循環綁定 |
| 字串模式 ❌ | setTimeout('fn('+arg+')', 1000) | 嚴禁:eval 風險、CSP 違規、除錯困難 |
// ❌ 錯誤:所有定時器共用同一個 i,最終皆輸出 3
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000); // 3, 3, 3
}
// ✅ 正確 1:let 區塊作用域(ES6+)
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000); // 0, 1, 2
}
// ✅ 正確 2:IIFE 捕獲當前值
for (var i = 0; i < 3; i++) {
((j) => setTimeout(() => console.log(j), 1000))(i); // 0, 1, 2
}
// ✅ 正確 3:bind 傳參
for (var i = 0; i < 3; i++) {
setTimeout(console.log.bind(console, i), 1000); // 0, 1, 2
}
const id = setTimeout(() => doSomething(), 5000);
clearTimeout(id); // 取消
// 批次管理
const timers = new Set();
function setTimeoutTracked(fn, delay, ...args) {
const id = setTimeout(() => { timers.delete(id); fn(...args); }, delay, ...args);
timers.add(id);
return id;
}
function clearAllTimeouts() { timers.forEach(clearTimeout); timers.clear(); }
// Promise 版 sleep(可 await、可取消)
function sleep(ms, signal) {
return new Promise((resolve, reject) => {
const id = setTimeout(resolve, ms);
signal?.addEventListener('abort', () => { clearTimeout(id); reject(new DOMException('Aborted', 'AbortError')); });
});
}
// 使用
const controller = new AbortController();
sleep(2000, controller.signal)
.then(() => console.log('2秒後執行'))
.catch(e => e.name === 'AbortError' && console.log('已取消'));
// 3秒後自動取消
setTimeout(() => controller.abort(), 3000);
setTimeout(fn, 0) 最小延遲約 4ms(HTML 標準),嵌套超過 5 層會被限制最小 4ms。setInterval + 時間戳檢查,或 requestAnimationFrame 統一調度。setTimeout 回呼在微任務隊列之後、宏任務隊列中執行,優先級低於 Promise.then。現代環境請直接使用 setTimeout(fn, delay, ...args) 原生傳參;舊環境用 箭頭函數包裹 最簡潔。循環綁定務必用 let 或 IIFE/bind 捕獲當前值。長期運行應用請建立定時器追蹤集合,統一清理防止記憶體洩漏。複雜非同步流程優先考慮 Promise + AbortController 替代裸 setTimeout。