萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 定時器詳解:setTimeout/setInterval 原理與最佳實踐

兩大定時器 API

方法類型語法返回值用途
setTimeout一次性setTimeout(fn, delay, ...args)timerId (Number)延遲執行、防抖、節流
setInterval循環setInterval(fn, delay, ...args)timerId (Number)輪詢、動畫、定時檢查

參數詳解


// 基礎用法
setTimeout(() => console.log('3秒後執行'), 3000);
setInterval(() => console.log('每秒執行'), 1000);

// 傳遞參數(現代語法,IE9+)
setTimeout((a, b) => console.log(a + b), 1000, 1, 2); // 3

// 取消
const timer = setTimeout(fn, 1000);
clearTimeout(timer);

const interval = setInterval(fn, 1000);
clearInterval(interval);

運行機制:事件循環視角


// setTimeout(fn, 0) 不代表立即執行!
console.log(1);
setTimeout(() => console.log(2), 0);
Promise.resolve().then(() => console.log(3));
console.log(4);

// 輸出順序:1, 4, 3, 2
// 解析:
// 1. 同步代碼 1, 4
// 2. 微任務 Promise.then → 3
// 3. 宏任務 setTimeout → 2

setTimeout 遞歸 vs setInterval


// 模式 A:setTimeout 遞歸(推薦用於動畫/不固定間隔)
function animate() {
    // ... 動畫邏輯
    if (shouldContinue) requestAnimationFrame(animate); // 更優
    // 或 setTimeout(animate, 16);
}

// 模式 B:setInterval(固定頻率輪詢)
const timer = setInterval(() => {
    if (shouldStop) clearInterval(timer);
    else doPolling();
}, 5000);

// 關鍵差異:
// setTimeout: 下一次執行時間 = 上次執行結束 + delay
// setInterval: 理論觸發時間 = 啟動時間 + n * delay (可能堆積)

常見陷阱與解決

1. 循環中閉包陷阱


for (var i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 100); // 輸出 3, 3, 3
}
// 修復:let / IIFE / bind
for (let i = 0; i < 3; i++) { // let 塊級作用域
    setTimeout(() => console.log(i), 100); // 0, 1, 2
}

2. this 綁定丟失


const obj = {
    name: 'Test',
    start: function() {
        setTimeout(function() {
            console.log(this.name); // undefined (this 指向 window)
        }, 100);
    }
};

// 修復
setTimeout(() => this.method(), 100);           // 箭頭函數
setTimeout(this.method.bind(this), 100);        // bind
setTimeout(function() { this.method(); }.bind(this), 100);

3. 頁面隱藏時暫停(Page Visibility API)


let timer;
function start() {
    timer = setInterval(doWork, 1000);
}
function stop() {
    clearInterval(timer);
}

document.addEventListener('visibilitychange', () => {
    if (document.hidden) stop();
    else start();
});

現代替代方案

需求推薦 API優勢
動畫幀requestAnimationFrame瀏覽器優化、電池友好、60fps 對齊
空閒時執行requestIdleCallback不阻塞高優先級工作
精確延遲setTimeout + performance.now()可測量實際延遲
Web Worker 定時Worker 內 setInterval不阻塞主線程

Node.js 環境差異

  • 返回值類型不同:瀏覽器返回 Number,Node 返回 Timeout 對象
  • Node 有 setImmediate、process.nextTick(微任務優先級最高)
  • clearTimeout/clearInterval 通用
copyright © 萬盛學電腦網 all rights reserved