如何设置获取此 websockets 数据的时间间隔?

how to set the interval at which this websockets data is fetched?

这是代码--->

const delay = 5000;
    
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);
    let price = parseFloat(stockObject.p).toFixed(2);
    priceElement1.innerText = price;
    priceElement1.style.color = !lastPrice1 || lastPrice1 === price ? 'white' : price > lastPrice1 ? '#AAFF00' : 'red';
    lastPrice1 = price;
};

我试图让它每 5000 毫秒而不是每 1 毫秒向元素流式传输数据。

这是我的第一个堆栈溢出 post 对不起,如果它不好我几个月前才开始接触 html css 和 js,我正在尝试处理更困难的任务.

谢谢!

一般情况下,websocket的数据不是fetch出来的,而是服务器发送过来后立即接收到的。这就是为什么首先使用 websockets 而不是其他方法(如 ajax 轮询)的原因。

在您的情况下,您可以简单地将收到的消息保存到一个变量中,并且只每 5 秒检查一次该变量的更新。 这可能看起来像这样:

const delay = 5000;

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

ws.onmessage = (event) => {
    stockObject = JSON.parse(event.data);
};

setInterval(() => {
    if(stockObject === null) {
        return;
    }
    let price = parseFloat(stockObject.p).toFixed(2);
    priceElement1.innerText = price;
    priceElement1.style.color = !lastPrice1 || lastPrice1 === price ? 'white' : price > lastPrice1 ? '#AAFF00' : 'red';
    lastPrice1 = price;
    stockObject = null;
}, delay);