萬盛學電腦網

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

JavaScript setTimeout 與 setInterval 差異詳解與最佳實務

setTimeout 與 setInterval 是 JS 兩大計時器 API,看似相似但行為本質不同。本文深入解析差異、常見陷阱、現代替代方案。

核心差異對照

特性setTimeoutsetInterval
執行次數一次重複執行
時間基準延遲指定毫秒後執行每隔指定毫秒執行一次
回傳值Timer ID(可 clearTimeout)Timer ID(可 clearInterval)
執行緒阻塞影響延遲執行,不影響間隔若回調執行時間 > 間隔,會堆疊/丟幀
適用場景延遲執行、去抖動、一次性任務輪詢、動畫循環、定期同步

基本語法

// setTimeout
const timeoutId = setTimeout(callback, delayMs, ...args);
clearTimeout(timeoutId);

// setInterval
const intervalId = setInterval(callback, intervalMs, ...args);
clearInterval(intervalId);

// 傳遞參數(現代瀏覽器支援第三參數起)
setTimeout((a, b) => console.log(a + b), 1000, 1, 2); // 1 秒後輸出 3

setInterval 致命缺陷:執行時間超過間隔


// 危險範例:回調耗時 200ms,間隔 100ms
setInterval(() => {
    heavyComputation(); // 耗時 200ms
}, 100);

// 結果:瀏覽器會嘗試追趕,導致:
// 1. 回調堆疊、記憶體暴增
// 2. 事件循環阻塞、UI 凍結
// 3. 某些瀏覽器會丟棄部分回調

安全替代:遞迴 setTimeout

function safeInterval(callback, interval) {
    let timerId;
    
    function tick() {
        const start = performance.now();
        callback();
        const elapsed = performance.now() - start;
        // 動態調整下一次延遲,確保間隔 ≥ 設定值
        const nextDelay = Math.max(0, interval - elapsed);
        timerId = setTimeout(tick, nextDelay);
    }
    
    tick(); // 立即執行第一次
    
    return {
        stop: () => clearTimeout(timerId),
        // 可選:動態調整間隔
        setInterval: (newInterval) => { interval = newInterval; }
    };
}

// 使用
const poller = safeInterval(() => {
    fetch('/api/status').then(r => r.json()).then(updateUI);
}, 5000);

// 隨時停止
poller.stop();

去抖動與節流

// 防抖:事件停止觸發 delay 後才執行
function debounce(fn, delay) {
    let timer;
    return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), delay);
    };
}

// 節流:固定間隔執行一次
function throttle(fn, interval) {
    let last = 0;
    return (...args) => {
        const now = Date.now();
        if (now - last >= interval) {
            last = now;
            fn.apply(this, args);
        }
    };
}

// 使用
window.addEventListener('resize', debounce(() => {
    console.log('視窗大小變更完成');
}, 300));

window.addEventListener('scroll', throttle(() => {
    console.log('滾動中...');
}, 100));

現代替代方案

requestAnimationFrame:動畫循環首選

function animate() {
    // 更新動畫狀態
    updatePhysics();
    render();
    // 瀏覽器決定下一幀最佳時機(通常 16.67ms)
    requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

setTimeout 0:讓出主執行緒

// 將耗時操作推到下一個事件循環
function processLargeArray(arr) {
    const chunk = arr.splice(0, 1000);
    chunk.forEach(heavyProcess);
    if (arr.length > 0) {
        setTimeout(() => processLargeArray(arr), 0); // 讓 UI 有機會回應
    }
}

Web Worker:真正多執行緒

// main.js
const worker = new Worker('worker.js');
worker.postMessage({ type: 'START', data: largeDataset });
worker.onmessage = e => console.log('結果:', e.data);

// worker.js
self.onmessage = e => {
    const result = heavyComputation(e.data.data);
    self.postMessage({ type: 'RESULT', data: result });
};

計時器精度與最小延遲

  • HTML5 規範最小間隔:4ms(嵌套超過 5 層後)
  • 背景分頁:最小間隔提升至 1000ms(節省電力)
  • 使用 performance.now() 測量高精度時間

記憶體洩漏防範

class TimerManager {
    constructor() {
        this.timers = new Map();
    }
    
    setTimeout(key, fn, delay) {
        this.clear(key);
        this.timers.set(key, setTimeout(fn, delay));
    }
    
    setInterval(key, fn, interval) {
        this.clear(key);
        this.timers.set(key, setInterval(fn, interval));
    }
    
    clear(key) {
        const id = this.timers.get(key);
        if (id) {
            clearTimeout(id); // clearTimeout/clearInterval 通用
            this.timers.delete(key);
        }
    }
    
    clearAll() {
        this.timers.forEach(id => clearTimeout(id));
        this.timers.clear();
    }
}

// 元件銷毀時自動清理
componentWillUnmount() {
    this.timerManager.clearAll();
}

總結

  • setTimeout:一次性延遲執行,安全可控
  • setInterval:固定間隔重複,**避免用於耗時回調**
  • 重複任務優先用遞迴 setTimeout或 requestAnimationFrame
  • 去抖動/節流是事件處理必備工具
  • 統一管理 Timer ID,元件銷毀時清理,防記憶體洩漏
copyright © 萬盛學電腦網 all rights reserved