每 3 秒将 console.log 结果存储到数组中

Store console.log result into array every 3 second

我正在尝试每秒仅从 Binance 获取比特币的价格,并将结果存储在一个数组中。我有以下代码,每次我想要最后的价格时都必须刷​​新页面。我也不确定如何在数组中输入它。

     var burl ='https://api.binance.com';

var query ='/api/v3/ticker/price';

query += '?symbol=BTCUSDT'; //&interval=15m&limit=2';

var url = burl + query;

var ourRequest = new XMLHttpRequest();

ourRequest.open('GET',url,true);
ourRequest.onload = function(){

  // Will convert the string to something Javascript can understand
  var result = JSON.parse(ourRequest.responseText); 

  // You can now use it as an array
  console.log(result);
}
ourRequest.send();

我也找到了一个 fetch 方法,我不知道如何修改这段代码来帮助我解决这个问题。

componentDidMount() {
    fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
        .then(response => {
            return response.json();
        })
        .then(data => {
            // Here you need to use an temporary array to store NeededInfo only 
            let tmpArray = []
            for (var i = 0; i < data.results.length; i++) {
                tmpArray.push(data.[i])
            }

            this.setState({
                other: tmpArray
            })
        });
} 

非常感谢!!

要每 3 秒发出一个请求,您需要使用 setInterval
要将响应价格推送到数组,您需要使用 array.push(price)

let array = [];
let eachEverySeconds = 3;

function fetchCoinPrice(params) {
  fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
    .then(response => {
        return response.json();
    })
    .then(data => {
        array.push(data.price)
        console.log("tmpArray", array);
    }); 
}

fetchCoinPrice();
setInterval(fetchCoinPrice, eachEverySeconds * 1000);