Home » Jquery » javascript – How can I automatically update the data from api, how can ı do-Exceptionshub

javascript – How can I automatically update the data from api, how can ı do-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I get data from an API, but not automatically updated.What can I do? How can it be updated automatically?

<div>
  <p id="pet">Lorem, ipsum dolor.</p>
</div>
var burl = "https://api.binance.com"
var query = "/api/v3/depth"
query += "?symbol=BTCUSDT&limit=5" //price
var url = burl + query;

var myrequest = new XMLHttpRequest();
myrequest.open("GET", url, true);

myrequest.onload = (function() {
  if (this.status == 200) {
    var dizi = new Array();
    dizi = JSON.parse(myrequest.responseText)
    var price = Number(dizi.asks[0][0]);
    console.log(typeof price)

    $("#pet").text(price)
  }
})
myrequest.send();
How to&Answer:

You can use setTimeout() function to call the API at regular intervals, like every 5 seconds. First you would have to move your code to a function and then call the function.

Lorem, ipsum dolor.

function getData(){
   var burl = "https://api.binance.com"
   var query = "/api/v3/depth"
   query += "?symbol=BTCUSDT&limit=5" //price
   var url = burl + query;

   var myrequest = new XMLHttpRequest();
   myrequest.open("GET", url, true);

   myrequest.onload = (function() {
      if (this.status == 200) {
         var dizi = new Array();
         dizi = JSON.parse(myrequest.responseText);
         var price = Number(dizi.asks[0][0]);
         console.log(typeof price);

         $("#pet").text(price);

         setTimeout(getData(), 5000); //5000 means 5 seconds
      }
   });
   myrequest.send();
}
getData();

Note I am not using setInterval() which calls the function over and over again. I am using settimeout() inside the success to make sure the next call is only called when the current call is finished.