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

如何设置WebSocket数据获取更新间隔,实现每5000ms更新一次?

实现方案

我们不需要限制WebSocket接收消息的频率,只需要把每次收到的最新价格缓存下来,每隔5秒统一将缓存的最新价格更新到页面上即可,这样既能保证你看到的是当前最新价格,也能避免DOM频繁刷新。

修改后完整代码

const delay = 5000;
// 新增变量:存储最新的价格缓存
let latestPrice = null;

let ws = new WebSocket('wss://stream.binance.com:9443/ws/ethusdt@trade');
let priceElement1 = document.getElementById('ethprice');
let lastPrice1 = null;

ws.onmessage = (event) => {
    let stockObject = JSON.parse(event.data);
    // 仅更新缓存,不直接操作DOM
    latestPrice = parseFloat(stockObject.p).toFixed(2);
};

// 新增定时器:每5秒更新一次页面元素
setInterval(() => {
    // 还未收到推送数据时不更新
    if (latestPrice === null) return;
    priceElement1.innerText = latestPrice;
    priceElement1.style.color = !lastPrice1 || lastPrice1 === latestPrice ? 'white' : latestPrice > lastPrice1 ? '#AAFF00' : 'red';
    lastPrice1 = latestPrice;
}, delay);

核心修改说明

  • 新增latestPrice变量专门缓存WebSocket推送的最新价格,收到推送时不再直接修改页面
  • 新增定时器按照设置的5000ms间隔,统一把缓存的最新价格更新到页面,完全保留了原有的涨跌色判断逻辑
  • 首次收到推送后第一次定时器触发就会显示价格,不会出现页面长时间空白的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:54:10