You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript:setTimeout中DOM事件未触发问题求助

Hey there, let's break down the issues in your code and fix them step by step!

Core Problems & Fixes

1. Variable Scope Trap Breaking setTimeout

You're using var i in your loop, and var has function-level scope—not block-level. By the time your setTimeout callbacks fire, the loop has already finished, and i will be stuck at 500 (the value that exits the loop). This means your callback is trying to target an element like cryptotable500 which almost certainly doesn't exist.

Fix: Replace var with let for your loop variable. let creates a new binding for i in each iteration of the loop, so the setTimeout callback will capture the correct value of i from that specific loop run.

2. Invalid CSS Color Value

You wrote #00000 as a color—CSS requires hex color values to be 3 or 6 characters long. This invalid value will be ignored by the browser.

Fix: Change it to #000 (short for black) or #000000.

Optimized & Fixed Code

I've also added some extra improvements to make your code cleaner and more performant:

for (let i = 0; i < 500; i++) { 
  const compare = cryptoSName[i].innerHTML;
  if (compare === crypto) { 
    // Cache DOM elements to avoid repeated getElementById calls
    const tableRow = document.getElementById(`cryptotable${i}`);
    const priceEl = document.getElementById(`price${i}`);
    const percEl = document.getElementById(`perc${i}`);

    // Update styles and content immediately
    tableRow.style.color = "#000"; 
    priceEl.innerHTML = "$" + tradeMsg.message.msg.price.toFixed(4);
    percEl.innerHTML = `${tradeMsg.message.msg.perc}%`;

    // Use the cached element in setTimeout
    setTimeout(function() { 
      tableRow.style.color = "#ff0000"; 
    }, 500); 
  } 
}

Extra Notes

  • Use const instead of var for variables that don't need reassigning—it makes your code safer and more readable.
  • Caching DOM elements (storing them in variables) reduces redundant DOM queries, which boosts performance.
  • Template strings (`cryptotable${i}`) make string concatenation cleaner than using +.
  • Using === (strict equality) instead of == avoids unexpected behavior from implicit type conversion.

内容的提问来源于stack exchange,提问作者user9504869

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:34:32