萬盛學電腦網

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

JavaScript 定時器完整指南:setTimeout、setInterval 進階用法與避坑

核心 API 對比

特性setTimeoutsetInterval
執行模式 單次延遲執行 周期性重複執行
返回值 timerId (正整數) timerId (正整數)
取消方法 clearTimeout(timerId) clearInterval(timerId)
典型場景 延遲初始化、防抖、動畫幀、倒計時跳轉 輪詢、心跳、定時刷新、動畫循環

基礎用法

單次定時器

// 函數引用方式(推薦)
var timer1 = setTimeout(hello, 1000);

// 字符串方式(不推薦,類似 eval)
var timer2 = setTimeout("hello()", 3000);

// 取消
clearTimeout(timer1);

循環定時器

var timer1 = setInterval(hello, 1000);
var timer2 = setInterval("hello()", 3000);
clearInterval(timer1);

進階技巧與最佳實踐

1. 模擬 setTimeout 實現 setInterval(避免執行時間累積誤差)

function mySetInterval(fn, delay) {
    var timer = null;
    function loop() {
        fn();
        timer = setTimeout(loop, delay);
    }
    timer = setTimeout(loop, delay);
    return {
        cancel: function() { clearTimeout(timer); }
    };
}

// 使用
var ticker = mySetInterval(function() {
    console.log('每秒執行,不受執行時長影響');
}, 1000);

// 停止
ticker.cancel();

優勢:每次間隔 = 設定延遲 + 函數執行時間,而非固定間隔發射,避免長任務導致的「疊加」問題。

2. requestAnimationFrame 替代動畫定時器

function animate() {
    // 更新動畫狀態
    requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

優勢:瀏覽器優化幀率、頁面不可見時自動暫停、電池友好。

3. 頁面加載順序控制

問題:多個 onload 回調執行順序不確定。

window.addEventListener('load', function() {
    // 延遲 0ms 將任務推入宏任務隊列末尾,確保其他 onload 先執行
    setTimeout(function() {
        initModuleA();
    }, 0);

    setTimeout(function() {
        initModuleB(); // 確保在 ModuleA 之後
    }, 0);
});

4. 可見性狀態感知定時器

var timer = null;
function startPolling() {
    timer = setInterval(fetchData, 5000);
}
function stopPolling() {
    clearInterval(timer);
    timer = null;
}

document.addEventListener('visibilitychange', function() {
    if (document.hidden) stopPolling();
    else startPolling();
});
startPolling();

5. 防抖與節流封裝

// 防抖:連續觸發只執行最後一次
function debounce(fn, delay) {
    var timer = null;
    return function(...args) {
        clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), delay);
    };
}

// 節流:固定頻率執行
function throttle(fn, interval) {
    var last = 0;
    return function(...args) {
        var now = Date.now();
        if (now - last >= interval) {
            last = now;
            fn.apply(this, args);
        }
    };
}

// 應用:輸入框搜尋建議
$('#search').on('input', debounce(function() {
    suggest(this.value);
}, 300));

// 應用:滾動事件節流
window.addEventListener('scroll', throttle(function() {
    checkLazyLoad();
}, 200));

常見陷阱與避坑指南

陷阱現象解決
字符串參數 setTimeout("fn()", 100) 存在注入風險、作用域混亂 永遠傳函數引用 setTimeout(fn, 100) 或箭頭函數
this 丟失 定時器回調中 this 指向 window 用箭頭函數、bind、或 var self = this
循環中閉包陷阱 for(var i=0;i<3;i++) setTimeout(()=>console.log(i),100) 輸出 3,3,3 用 let、IIFE、或傳參 setTimeout((i)=>..., 100, i)
未清理導致記憶體洩漏 組件銷毀時定時器仍在運行 在 componentWillUnmount/beforeDestroy 中 clearTimeout/clearInterval
大量 setTimeout 造成主線程阻塞 幾百個同時定時器導致頁面卡頓 合併邏輯、使用 Web Worker、requestIdleCallback

實戰案例:倒計時跳轉組件

function CountdownRedirect(seconds, targetUrl, options = {}) {
    const { onTick, elementId } = options;
    const el = elementId ? document.getElementById(elementId) : null;
    let remaining = seconds;

    const tick = () => {
        if (el) el.textContent = remaining;
        onTick?.(remaining);
        if (remaining <= 0) {
            window.location.href = targetUrl;
            return;
        }
        remaining--;
        timer = setTimeout(tick, 1000);
    };

    let timer = setTimeout(tick, 1000);

    return {
        cancel: () => clearTimeout(timer),
        restart: (newSec) => { clearTimeout(timer); remaining = newSec; tick(); }
    };
}

// 使用
const cd = CountdownRedirect(5, '/home', {
    elementId: 'countdown',
    onTick: (s) => console.log(`剩餘 ${s} 秒`)
});

結語

定時器是 JavaScript 異步編程的基石。掌握 setTimeout/setInterval 的微任務/宏任務機制、this 綁定、清理時機,並結合 requestAnimationFrame、Visibility API、防抖節流等進階模式,能寫出高性能、無洩漏的異步邏輯。

copyright © 萬盛學電腦網 all rights reserved