在特定秒内更新的比特币价格

Bitcoin Price that updates in specific Seconds

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

<pre><code><!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>

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

您需要使用 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

将对 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 = "[=10=].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>

这是示例

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>