Home > Software design >  how to display API requests in real time?
how to display API requests in real time?

Time:11-14

I want to send a request to API every 10 - 20 seconds and update it on my webpage how can I do that

code is this :

const api_url = 'https://min-api.cryptocompare.com/data/price?fsym=LTC&tsyms=USD' // api to get price from
 
  const getPrice = async () => {
       const response = await fetch(api_url);
       const data = await response.json();
       return parseFloat(data.USD)
   }
   
 
   const calculate = async () => { // price that gets from API and balance in LTC converts to USD
       const balancee = balance / 1e8 // this is where balance in LTC gets so can convert later in USD
       const price = await getPrice()
       const result = price * balancee.toFixed(2)
       document.querySelector('#price').innerText = result   " USD"; // this displays on my webpage in <span> element
   }
   
   calculate();

CodePudding user response:

You can use setInterval:

calculate()
setInterval(() => {
  calculate()
}, 20000) // call calculate function every 20 sec
  • Related