简体   繁体   English

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

[英]Store console.log result into array every 3 second

I am trying to get the price only of bitcoin from Binance for each second and store the result in an array.我试图每秒只从 Binance 获取比特币的价格并将结果存储在一个数组中。 I have the following code, I have to refresh the page everytime I want the last price.我有以下代码,每次我想要最后价格时都必须刷​​新页面。 I am also not sure how to input that in an array.我也不确定如何将其输入到数组中。

     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();

I also find a fetch method, I am not sure how to adapt this code to help me solve this issue.我也找到了一个 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
            })
        });
} 

Thank you so much!!非常感谢!!

To give a request every 3 seconds you need to use setInterval要每 3 秒发出一次请求,您需要使用 setInterval
To push response price to array you need to use array.push(price)要将响应价格推送到数组,您需要使用 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM