萬盛學電腦網

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

JavaScript setTimeout 傳參完整指南:從基礎到閉包陷阱解決

基礎傳參語法

setTimeout(function() { cao(a); }, 3000); // 匿名函數包裝
setTimeout(cao, 3000, a); // 現代瀏覽器支持直接傳參(IE9+ 不支持)

循環閉包陷阱

// 錯誤:所有定時器共享同一 i
for (var i = 0; i < points.length; i++) {
    setTimeout(function() { AddGuiJi(points[i], value); }, 2000 * i);
}

三大解決方案

1. IIFE 立即執行函數捕獲

for (var i = 0; i < points.length; i++) {
    (function(index) {
        setTimeout(function() { AddGuiJi(points[index], value); }, 2000 * index);
    })(i);
}

2. let 塊級作用域(ES6+ 推薦)

for (let i = 0; i < points.length; i++) {
    setTimeout(function() { AddGuiJi(points[i], value); }, 2000 * i);
}
// 每次迭代創建新綁定,自動解決

3. 遞歸鏈式調用(順序執行場景)

var timer, index = 0;
function loop(points, value) {
    if (index < points.length) {
        AddGuiJi(points[index], value);
        index++;
        timer = setTimeout(function() { loop(points, value); }, 1000);
    } else {
        index = 0;
        clearTimeout(timer);
    }
}

現代最佳實踐:Promise + async/await

const delay = (ms) => new Promise(r => setTimeout(r, ms));

async function sequentialProcess(points, value) {
    for (const p of points) {
        AddGuiJi(p, value);
        await delay(1000);
    }
}

// 並行控制(如限制併發)
async function concurrentProcess(points, value, limit = 3) {
    const queue = [...points];
    const workers = Array(limit).fill().map(async () => {
        while (queue.length) {
            const p = queue.shift();
            AddGuiJi(p, value);
            await delay(1000);
        }
    });
    await Promise.all(workers);
}

選型指南

場景推薦方案
簡單單次延遲箭頭函數包裝
循環並行定時器let + 箭頭函數
順序執行/間隔固定遞歸鏈式 / async-await
複雜併發控制Promise 隊列 / p-limit 庫
copyright © 萬盛學電腦網 all rights reserved