0

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?

Stan Daily
  • 79
  • 4
  • You should be able to use it outside the event handler. Of course, you can only use it *after* the event has occurred, not immediately after assigning the handler. – Barmar Sep 29 '21 at 14:56
  • `ethprice` is local to the function, I was talking about `ethlastpPrice`. – Barmar Sep 29 '21 at 14:58
  • @Barmar so if i try and console.log(ethlastPrice) I get null which I assume is because that's what i originally set it. How can I get ethlastPrice to continuously update so it's constantly got the new live price? Thanks for your response btw! – Stan Daily Sep 29 '21 at 15:01
  • Add a button that executes `console.log(ethlastPrice)` in its click listener. Click on the button after the `onmessage` function displays the price. – Barmar Sep 29 '21 at 15:02
  • @Barmar could you point me in the direction of any kind of documentation for this. I'm new so not 100% sure what I'm looking for. – Stan Daily Sep 29 '21 at 15:16
  • See the link I added above the question. – Barmar Sep 29 '21 at 15:18

0 Answers0