如何处理多个setTimeout实例并在两HTML列每10秒展示BTC价格?
解决两列显示BTC价格的问题
问题根源
- HTML重复ID:你给两个价格展示的span用了同一个ID
stock-price-10-sec,但ID在页面中必须唯一,getElementById只会获取到第一个元素,导致第二列无法显示内容。 - 单次执行的定时器:原代码用
setTimeout,只会执行一次,没法实现每10秒自动更新的需求,应该改用setInterval来重复执行更新逻辑。
修正后的代码
HTML代码
<table class="col-md-12 table-bordered table-striped table-condensed cf "> <thead class="cf"> <tr> <th>Current course</th> <th class="numeric w7 text-center">Value 1</th> <th class="numeric w7 text-center">Value 2</th> </tr> </thead> <tbody> <tr> <td>BTC</td> <td class="numeric"><span id="stock-price-10-sec-1"></span></td> <td class="numeric"><span id="stock-price-10-sec-2"></span></td> </tr> </tbody> </table>
JS代码
let ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade'); // 获取两个不同ID的价格展示元素 let stockPriceElement1 = document.getElementById('stock-price-10-sec-1'); let stockPriceElement2 = document.getElementById('stock-price-10-sec-2'); let lastPrice = null; let stockObject = null; ws.onmessage = (event) => { stockObject = JSON.parse(event.data); }; // 用setInterval实现每10秒重复更新价格 setInterval(() => { if(stockObject === null) { return; } let price = parseFloat(stockObject.p).toFixed(2); // 同步更新两列的价格文本 stockPriceElement1.innerText = price; stockPriceElement2.innerText = price; // 统一设置价格涨跌颜色 const priceColor = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? '#AAFF00' : 'red'; stockPriceElement1.style.color = priceColor; stockPriceElement2.style.color = priceColor; lastPrice = price; stockObject = null; }, 10000);
额外说明
如果后续需要让两列展示不同的价格逻辑(比如记录不同时间点的价格),可以单独为每列维护lastPrice变量(比如lastPrice1和lastPrice2),再分别处理颜色和更新逻辑即可。
内容的提问来源于stack exchange,提问作者elodie
相关产品推荐
相关产品推荐

