const timerId = setTimeout(callback, delay, ...args);
callback:延遲執行的函式delay:毫秒數 (最小 4ms,巢狀超過 5 層會被夾帶)...args:傳給 callback 的參數 (IE9- 不支援,需用閉包/bind)timerId:供 clearTimeout 取消| 特性 | 說明 |
|---|---|
| 單次執行 | 只執行一次,需重複請用 setInterval 或遞迴 setTimeout |
| 非阻塞 | 不阻塞主執行緒,屬於宏任務 |
| 最小延遲 | HTML5 規範 4ms (巢狀 >5 層),實際受事件迴圈影響 |
| this 綁定 | 預設 window/global,需用箭頭函式/.bind()/閉包固定 |
// ❌ 錯誤:全部輸出 5
for (var i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 100);
}
// ✅ 方案一:let 區塊作用域 (ES6)
for (let i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 100); // 0,1,2,3,4
}
// ✅ 方案二:IIFE 建立閉包
for (var i = 0; i < 5; i++) {
((j) => setTimeout(() => console.log(j), 100))(i);
}
// ✅ 方案三:傳參數 (setTimeout 第三參數)
for (var i = 0; i < 5; i++) {
setTimeout((j) => console.log(j), 100, i);
}
const obj = {
name: 'Test',
greet() { console.log(this.name); }
};
// ❌ 1 秒後輸出 undefined (this 指向 window)
setTimeout(obj.greet, 1000);
// ✅ 箭頭函式
setTimeout(() => obj.greet(), 1000);
// ✅ bind
setTimeout(obj.greet.bind(obj), 1000);
// ✅ 閉包
const self = obj;
setTimeout(function() { self.greet(); }, 1000);
setTimeout(() => console.log('A'), 0);
console.log('B');
// 輸出順序:B → A
// 原因:setTimeout 為宏任務,當前調用棧清空後才執行
function debounce(fn, wait) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
}
// 使用:輸入框搜尋建議
const debouncedSearch = debounce(query => api.search(query), 300);
input.addEventListener('input', e => debouncedSearch(e.target.value));
function throttle(fn, interval) {
let last = 0;
return function(...args) {
const now = Date.now();
if (now - last >= interval) {
last = now;
fn.apply(this, args);
}
};
}
// 使用:滾動事件
window.addEventListener('scroll', throttle(() => updateNav(), 200));
function repeatTask() {
doWork().then(() => {
setTimeout(repeatTask, getDynamicInterval()); // 依條件調整間隔
});
}
repeatTask();
const timers = new Set();
const originalSetTimeout = window.setTimeout;
window.setTimeout = function(fn, delay, ...args) {
const id = originalSetTimeout(fn, delay, ...args);
timers.add(id);
return id;
};
const originalClearTimeout = window.clearTimeout;
window.clearTimeout = function(id) {
timers.delete(id);
return originalClearTimeout(id);
};
function clearAllTimeouts() {
timers.forEach(id => clearTimeout(id));
timers.clear();
}
window.addEventListener('beforeunload', clearAllTimeouts);
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// 使用 async/await 寫法更直觀
async function demo() {
console.log('開始');
await delay(1000);
console.log('1秒後');
await delay(500);
console.log('再0.5秒後');
}
requestIdleCallback(deadline => {
while (deadline.timeRemaining() > 0 && taskQueue.length) {
taskQueue.shift()();
}
if (taskQueue.length) requestIdleCallback(arguments.callee);
});
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ data: largeArray });
worker.onmessage = e => console.log('結果:', e.data);
// worker.js
self.onmessage = e => {
const result = heavyComputation(e.data.data);
self.postMessage(result);
};
setTimeout 是 JS 非同步編程基石。掌握 事件迴圈機制、閉包陷阱、this 綁定、遞迴替代 setInterval 是進階開發必備。現代專案優先使用 Promise + async/await 管理非同步流程,debounce/throttle 處理高頻事件,Web Workers 卸載重計算。