Home > Blockchain >  How to handle multiple instances of setTimeout()?
How to handle multiple instances of setTimeout()?

Time:12-23

I found a solution below, but it's too hard for me to understand.

How do you handle multiple instances of setTimeout()?

I want to display on two HTML columns, the price of BTC every 10 seconds. I managed to do this only for one column.

Do you know how I can display the data on the second column also?

image

Here is my code JS

let ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
let stockPriceElement10sec = document.getElementById('stock-price-10-sec');
let lastPrice = null
let stockObject = null;

let myvar;

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



setTimeout(() => {
    if(stockObject === null) {
        return;
    }
    let price = parseFloat(stockObject.p).toFixed(2);
    stockPriceElement10sec.innerText = price;
    stockPriceElement10sec.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? '#AAFF00' : 'red';
    lastPrice = price;
    stockObject = null;
}, 10000);

HTML

            <table >
              <thead >
                <tr>
                  <th>Current course</th>
                  <th >Value 1</th>
                  <th >Value 2</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>BTC</td>
                  <td ><span id="stock-price-10-sec"></span></td>    
                  <td ><span id="stock-price-10-sec"></span></td>    
                </tr>
              </tbody>
            </table>

CodePudding user response:

In HTML, ids must be unique because you can only get the first element that has an id. You could use two different ids for the span elements.

<td ><span id="stock-price-10-sec-1"></span></td>
<td ><span id="stock-price-10-sec-2"></span></td>

Instead of getting just one of the elements, you can get both of them.

let stockPriceElement10sec1 = document.getElementById('stock-price-10-sec-1');
let stockPriceElement10sec2 = document.getElementById('stock-price-10-sec-2');

In your setTimeout handler, add code to update the second one as well.

stockPriceElement10sec1.innerText = price;
stockPriceElement10sec1.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? '#AAFF00' : 'red';

stockPriceElement10sec2.innerText = price;
stockPriceElement10sec2.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? '#AAFF00' : 'red';
  • Related