基礎語法與陷阱
// 基本:延遲執行函式
setTimeout(function() { console.log('Hello'); }, 1000);
// ❌ 陷阱 1:直接呼叫函式而非傳遞引用
setTimeout(foo(), 1000); // 立即執行 foo(),傳遞其回傳值 (通常是 undefined)
// ❌ 陷阱 2:字串參數 (eval 風險、效能差、作用域問題)
setTimeout("foo()", 1000); // 不推薦
// ✅ 正確:傳遞函式引用
setTimeout(foo, 1000);
setTimeout(() => foo(), 1000);
傳遞參數的三種方式
1. 箭頭函式 / 匿名函式包裝 (最常用)
function greet(name, age) {
console.log(`Hello ${name}, age ${age}`);
}
setTimeout(() => greet('Alice', 25), 1000);
// 或
setTimeout(function() { greet('Alice', 25); }, 1000);
2. bind 綁定 this 與參數
const obj = {
name: 'Bob',
greet(age) { console.log(`${this.name}, ${age}`); }
};
// bind 回傳新函式,this 固定為 obj,參數預設
setTimeout(obj.greet.bind(obj, 30), 1000); // "Bob, 30"
3. 原生支援 (現代瀏覽器/Node.js) - 第三參數起為傳遞參數
// 標準 HTML Living Standard / Node.js 10+
setTimeout(greet, 1000, 'Charlie', 35); // "Charlie, 35"
// 注意:IE 不支援,需 polyfill 或用箭頭函式
循環定時器:setTimeout 遞迴 vs setInterval
為什麼推薦 setTimeout 遞迴?
| 特性 | setInterval | setTimeout 遞迴 |
| 執行間隔保證 | 無 (若執行時間 > 間隔,會堆疊/掉幀) | 有 (上一輪結束後才排程下一輪) |
| 動態調整間隔 | 困難 (需 clear/set) | 容易 (下一輪傳新延遲) |
| 錯誤處理 | 錯誤不影響下一輪 | 需 try-catch 包裹遞迴呼叫 |
| 記憶體洩漏風險 | 低 | 若忘記停止會持續遞迴 |
標準循環模式
function startTicker(intervalMs) {
let timerId = null;
let running = false;
function tick() {
if (!running) return;
try {
// 你的邏輯
console.log('Tick at', new Date().toISOString());
} finally {
// 確保即使拋錯也能排程下一輪 (視需求)
timerId = setTimeout(tick, intervalMs);
}
}
return {
start() { running = true; tick(); },
stop() { running = false; clearTimeout(timerId); },
setInterval(ms) { intervalMs = ms; }
};
}
const ticker = startTicker(1000);
// ticker.stop();
// ticker.setInterval(2000);
Promise 包裝:現代非同步流程控制
// 基礎包裝
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// 使用
async function demo() {
console.log('Start');
await delay(1000);
console.log('After 1s');
await delay(500);
console.log('After 1.5s');
}
// 帶取消功能
function delayCancellable(ms) {
let timeoutId;
const promise = new Promise((resolve, reject) => {
timeoutId = setTimeout(resolve, ms);
});
promise.cancel = () => clearTimeout(timeoutId);
return promise;
}
// 競態:超時控制
async function fetchWithTimeout(url, timeoutMs = 5000) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(url, {signal: controller.signal});
return res;
} finally {
clearTimeout(timeout);
}
}
this 綁定陷阱完整解析
const obj = {
value: 42,
method() { console.log(this.value); }
};
setTimeout(obj.method, 100); // undefined (this = window/global)
setTimeout(obj.method.bind(obj), 100); // 42 ✅
setTimeout(() => obj.method(), 100); // 42 ✅ (箭頭函式捕獲外層 this)
setTimeout(function() { obj.method(); }, 100); // 42 ✅
// 類別方法同理
class Counter {
constructor() { this.count = 0; }
increment() { this.count++; }
log() { console.log(this.count); }
}
const c = new Counter();
setTimeout(c.log, 100); // 0 或錯誤 (this 丟失)
setTimeout(c.log.bind(c), 100); // 1 ✅
setTimeout(() => c.log(), 100); // 1 ✅
記憶體洩漏防範
class Component {
constructor() {
this.timerId = null;
}
startPolling() {
this.stopPolling(); // 防重複
this.timerId = setTimeout(() => this.poll(), 5000);
}
poll() {
fetchData().then(data => {
this.update(data);
if (!this.destroyed) this.timerId = setTimeout(() => this.poll(), 5000);
}).catch(err => {
console.error(err);
if (!this.destroyed) this.timerId = setTimeout(() => this.poll(), 30000); // 退避重試
});
}
stopPolling() {
if (this.timerId) {
clearTimeout(this.timerId);
this.timerId = null;
}
}
destroy() {
this.destroyed = true;
this.stopPolling();
}
}
Node.js 特有:setImmediate、process.nextTick、unref
// setImmediate: 下一個事件循環迴圈 (I/O 回呼之後)
setImmediate(() => console.log('immediate'));
// process.nextTick: 當前操作結束前 (微任務隊列前)
process.nextTick(() => console.log('nextTick'));
// 順序: nextTick → Promise.then → setImmediate → setTimeout
// timer.unref(): 不阻塞事件循環退出
const timer = setTimeout(() => console.log('unref'), 1000);
timer.unref(); // 程式可在 1 秒前正常退出
// timer.ref() 可恢復阻塞
總結最佳實踐
- 傳遞參數:現代環境用
setTimeout(fn, ms, ...args),否則用箭頭函式
- 循環任務:優先
setTimeout 遞迴,需動態間隔/錯誤隔離
- this 綁定:
bind、箭頭函式、包裝函式三選一
- 元件生命週期:
clearTimeout 配合 destroyed 標記防洩漏
- 非同步流程:
Promise 包裝 delay,搭配 AbortController 超時控制