Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
Using WebSocket data outside of onmessage event

Hey so I've been playing around with JavaScript learning in my free time and had a quick question. I am using websockets to look at crypto prices as shown in the code below:

let ethws = new WebSocket('wss://stream.binance.com:9443/ws/ethusdt@trade');
let btcws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
let ethstockPriceElement = document.getElementById('eth-stock-price')
let btcstockPriceElement = document.getElementById('btc-stock-price')
let ethlastPrice = null;
let btclastPrice = null;

ethws.onmessage = (event) => {
    let ethstockObject = JSON.parse(event.data)
    let ethprice = parseFloat(ethstockObject.p).toFixed(2)
    ethstockPriceElement.innerText = ethprice
    ethstockPriceElement.style.color = !ethlastPrice || ethlastPrice === ethprice ? 'black' : ethprice > ethlastPrice ? 'green' : 'red';
    ethlastPrice = ethprice
}
btcws.onmessage = (event) => {
    let btcstockObject = JSON.parse(event.data)
    let btcprice = parseFloat(btcstockObject.p).toFixed(2)
    btcstockPriceElement.innerText = btcprice
    btcstockPriceElement.style.color = !btclastPrice || btclastPrice === btcprice ? 'black' : btcprice > btclastPrice ? 'green' : 'red';
    btclastPrice = btcprice
}

I was wanting to use push the price into an "updating" variable outside of the event so I could do something like 2btc price 3eth price then btcprice + ethprice to get a total live updating price of 2btc and 3eth. However I am unable to use the data outside of the event. What would be the best way to achieve this?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda