【问题标题】:Bitcoin Price that updates in specific Seconds在特定秒内更新的比特币价格
【发布时间】:2020-08-16 15:05:36
【问题描述】:

我已经进行了一段时间的搜索,但没有运气,我有 html/javascript 代码,它可以从 bitcoininfo 检索并显示以美元为单位的比特币价格,但是我希望它使用 Javascript 每 5 秒自我更新一次。这样,无需刷新页面即可获得当前价格。我的代码是

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Bitcoin Current price</title>
  <style>#wrapper {
  font-size: 1em;
  font-family: arial;
  margin: 20px auto;
  width:450px;
  color: green;
  text-align: center;
}

#btc {font-size:6em;}

</style>
</head>
<body>
<!-- partial:index.partial.html -->
<div id="wrapper">
  <h1>Bitcoin Current Price</h1>
  <div id="btc"></div>
</div>
<!-- partial -->
  <script> var currentPrice = new XMLHttpRequest();

currentPrice.open('GET', 'https://api.gdax.com/products/BTC-USD/book', true);
currentPrice.onreadystatechange = function(){
  if(currentPrice.readyState == 4){
    var ticker = JSON.parse(currentPrice.responseText);
    var price = ticker.bids[0][0];
    document.getElementById('btc').innerHTML = "$" + price;
  };
};
currentPrice.send();</script>

</body>
</html>

如果有更好的方法,我们将不胜感激。

【问题讨论】:

  • 您可以使用“window.setInterval”函数,每5秒调用一次API
  • Javascript 不太好,您能否通过发布我应该用作答案的代码来使其更容易?
  • setInterval(myFunction, myNumberOfSeconds * 1000);

标签: javascript html bitcoin price ticker


【解决方案1】:

将对 API 的调用封装到一个函数中,然后使用 setInterval 每 5 秒重复调用一次。

如果有更好的方法来做到这一点,fetch API 得到了广泛的支持,并且有更好的 API

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Bitcoin Current price</title>
  <style>
    #wrapper {
      font-size: 1em;
      font-family: arial;
      margin: 20px auto;
      width: 450px;
      color: green;
      text-align: center;
    }
    
    #btc {
      font-size: 6em;
    }
  </style>
</head>

<body>
  <!-- partial:index.partial.html -->
  <div id="wrapper">
    <h1>Bitcoin Current Price</h1>
    <div id="btc"></div>
  </div>
  <!-- partial -->
  <script>
    function get_price() {
      var el = document.getElementById('btc')
      fetch("https://api.gdax.com/products/BTC-USD/book")
        .then(res => res.json())
        .then(res => {
          var price = res.bids[0][0];
          el.innerHTML = "$" + price;
        }).catch(err => {
          el.innerHTML = "$0.00 - Error";
        });
    }

    get_price()

    setInterval(get_price, 5000)
  </script>

</body>

</html>

或者使用websocket,例如:

function initWebSocket(products) {

  const ws = new WebSocket("wss://ws-feed.gdax.com");

  ws.onopen = function() {
    ws.send(JSON.stringify({
      "type": "subscribe",
      "channels": [{
        "name": "ticker",
        product_ids: Object.keys(products)
      }]
    }));
  };

  ws.onmessage = function(evt) {
    let data = JSON.parse(evt.data);
    if (typeof products[data.product_id] !== 'undefined') {
      products[data.product_id][data.side] = data
    }
  };

  ws.onclose = function() {
    console.log("Connection is closed...");
  };
}

function update() {
  for (let product_id in products) {
    let el = document.querySelector('[data-product="' + product_id + '"]')
    // buy
    el.getElementsByClassName('buy price')[0].innerHTML = products[product_id].buy.price
    el.getElementsByClassName('buy open_24h')[0].innerHTML = products[product_id].buy.open_24h
    el.getElementsByClassName('buy low_24h')[0].innerHTML = products[product_id].buy.low_24h
    el.getElementsByClassName('buy high_24h')[0].innerHTML = products[product_id].buy.high_24h
    el.getElementsByClassName('buy time')[0].innerHTML = products[product_id].buy.time
    // sell
    el.getElementsByClassName('sell price')[0].innerHTML = products[product_id].sell.price
    el.getElementsByClassName('sell open_24h')[0].innerHTML = products[product_id].sell.open_24h
    el.getElementsByClassName('sell low_24h')[0].innerHTML = products[product_id].sell.low_24h
    el.getElementsByClassName('sell high_24h')[0].innerHTML = products[product_id].sell.high_24h
    el.getElementsByClassName('sell time')[0].innerHTML = products[product_id].sell.time
  }
}

const products = {};
[...document.querySelectorAll('[data-product]')].forEach(
  el => products[el.getAttribute('data-product')] = {
    buy: {},
    sell: {}
  }
)

initWebSocket(products);

setInterval(update, 1000)
h1 {
  font-size: 24px;;
  text-align: center;
  font-weight: bold;
}

.text-center {
  text-align: center;
}

li {
  list-style: none;
}
<h1>ws-feed.gdax.com</h1>

<div data-product="BTC-USD" class="text-center">
  <strong>BTC-USD:</strong>
  <ul>
    <li>
      <strong>Buy:</strong> Price: <span class="buy price">0.00</span> Open 24h: <span class="buy open_24h">0.00</span> Low 24h: <span class="buy low_24h">0.00</span> High 24h: <span class="buy high_24h">0.00</span> Last: <span class="buy time"></span>
    </li>
    <li>
      <strong>Sell:</strong> Price: <span class="sell price">0.00</span> Open 24h: <span class="sell open_24h">0.00</span> Low 24h: <span class="sell low_24h">0.00</span> High 24h: <span class="sell high_24h">0.00</span> Last: <span class="sell time"></span>
    </li>
  </ul>
</div>

<div data-product="ETH-USD" class="text-center">
  <strong>ETH-USD:</strong>
  <ul>
    <li>
      <strong>Buy:</strong> Price: <span class="buy price">0.00</span> Open 24h: <span class="buy open_24h">0.00</span> Low 24h: <span class="buy low_24h">0.00</span> High 24h: <span class="buy high_24h">0.00</span> Last: <span class="buy time"></span>
    </li>
    <li>
      <strong>Sell:</strong> Price: <span class="sell price">0.00</span> Open 24h: <span class="sell open_24h">0.00</span> Low 24h: <span class="sell low_24h">0.00</span> High 24h: <span class="sell high_24h">0.00</span> Last: <span class="sell time"></span>
    </li>
  </ul>
</div>

【讨论】:

    【解决方案2】:

    这里是示例

    var interval = 3000; // Interval
    var currentPrice = new XMLHttpRequest(); 
    currentPrice.onreadystatechange = function() { 
      if(currentPrice.status == 200) {
        if ( currentPrice.responseText != '' ) {
          var ticker = JSON.parse(currentPrice.responseText);
          var price = ticker.bids[0][0];
          document.getElementById('btc').innerHTML = "$" + price;
          } 
        
      } 
      if ( currentPrice.readyState == 2 ) {  // check previous API call executed before call API again
          setTimeout(function() {
            getStockPrice();
        }, interval);
      } 
    };
    function getStockPrice() {
      currentPrice.open('GET', 'https://api.gdax.com/products/BTC-USD/book', true);
      currentPrice.send();
    } 
    getStockPrice();
    #wrapper {
      font-size: 1em;
      font-family: arial;
      margin: 20px auto;
      width:450px;
      color: green;
      text-align: center;
    }
    
    #btc {font-size:6em;}
    <div id="wrapper">
      <h1>Bitcoin Current Price</h1>
      <div id="btc"></div>
    </div>

    【讨论】:

      【解决方案3】:

      您需要使用setInterval(function, milliseconds) 函数来执行此操作。它将以指定的时间间隔(以毫秒为单位)调用函数或评估表达式。

      你的 javascript 代码会变成这样:

      function getPrice() {
        var currentPrice = new XMLHttpRequest();
        currentPrice.open('GET', 'https://api.gdax.com/products/BTC-USD/book', true);
        currentPrice.onreadystatechange = function() {
          if(currentPrice.readyState == 4){
            var ticker = JSON.parse(currentPrice.responseText);
            var price = ticker.bids[0][0];
            document.getElementById('btc').innerHTML = "$" + price;
          };
        };
        currentPrice.send();
      }
      // To send a request for the first time the page loads
      getPrice()
      setInterval(getPrice, 5000);
      

      有关此功能的更多信息,请参阅: https://www.w3schools.com/jsref/met_win_setinterval.asp

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-11
        • 2014-03-31
        • 1970-01-01
        • 2020-03-25
        • 1970-01-01
        • 2021-09-15
        相关资源
        最近更新 更多