-2

This function works for a single data item but it should keep refreshing every few seconds. How does this repeat?

   async function get_iss() {
       const response = await fetch('https://api.wheretheiss.at/v1/satellites/25544');
       const data = await response.json();
       document.getElementById("ISSdata").innerHTML = data.altitude;
       Textbox1.value = data.longitude;
       Textbox2.value = data.latitude;
   }
   get_iss();>
Solstice
  • 25
  • 6
  • 1
    Does this answer your question? [Calling a function every 60 seconds](https://stackoverflow.com/questions/3138756/calling-a-function-every-60-seconds) – Andrea Olivato Mar 21 '22 at 02:01
  • That is the ticket it updates it every 5000milliseconds with the setInterval(fn,5000); – Solstice Mar 21 '22 at 02:14
  • @AndreaOlivato intervals won't work since the browser gets reloaded. Simply execute `setTimeout(window.refresh, EVERY_HOW_LONG)` on page load. – code Mar 21 '22 at 02:29

1 Answers1

1

async function getIss() {
  // make request
  const response = await fetch('https://api.wheretheiss.at/v1/satellites/25544');
  const data = await response.json();
  // update UI
  document.getElementById("altitude").textContent = data.altitude;
  document.getElementById("lat").textContent = data.latitude;
  document.getElementById("lng").textContent = data.longitude;
}

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("Starting requesting data...");
  // load data once
  getIss()
  // define interval
  const seconds = 2;
  // execute the function every x seconds (safe interval ID so we can stop the interval later)
  const interval = setInterval(getIss, seconds * 1000)

  // stop after 10 seconds here (just to not go overboard with requests here, you might not need this)
  setTimeout(() => {
    clearInterval(interval);
    console.log("Stopped requesting data.")
  }, 10 * 1000)
});
<div>
  <span>Altitude:</span>
  <span id="altitude"></span>
  <span>Lat:</span>
  <span id="lat"></span>
  <span>Lng:</span>
  <span id="lng"></span>
</div>
Mushroomator
  • 6,516
  • 1
  • 10
  • 27