0

I have a script to fetch API data and display in span, all works with out any issues but i will like to add auto refresh every 5 sec for span element

const url =
  'https://api.helium.io/v1/validators/rewards/sum?min_time=2021-07-01T06:42:57Z'

fetch(url)
  .then((response) => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error("network bad");
    }
  })
  .then(function(data) {
    const total = data.data.total
    displayTotal(total);
    console.log(total);

  })
  .catch((error) => {
    console.error("fetch error;", error);
  })

function displayTotal(total) {
  document.getElementById("total").innerText = total.toLocaleString(2);

}
<span id='total' />
mar24n
  • 123
  • 2
  • 10
  • 1
    Does this answer your question? [Calling a function every 60 seconds](https://stackoverflow.com/questions/3138756/calling-a-function-every-60-seconds) – brc-dd Jul 16 '21 at 08:03

2 Answers2

2

Note I call the function in the success instead of using setInterval which will never stop even when errors and will cancel an ongoing call if it takes longer than 5 seconds. It is very unpleasnt for a server in trouble to have interval hammering it

const url =
  'https://api.helium.io/v1/validators/rewards/sum?min_time=2021-07-01T06:42:57Z'
const getTotal = () => {
  fetch(url)
    .then((response) => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error("network bad");
      }
    })
    .then(function(data) {
      const total = data.data.total
      displayTotal(total);
      console.log(total);
      setTimeout(getTotal, 5000);
    })
    .catch((error) => {
      console.error("fetch error;", error);
      // setTimeout(getTotal,5000); // uncomment if you want to keep trying even when error    
    })
}

function displayTotal(total) {
  document.getElementById("total").innerText = total.toLocaleString(2);
}
getTotal(); // start the calls
<span id="total"></span>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

The answer from mplungjan is good but, the setTimeout will never launch if there is an error in the first call. Instead it could be nice to wrap the wall call in the setTimeout function and then get the interval id so that you can stop it when you wan

Ingenious_Hans
  • 724
  • 5
  • 16