Home > OS >  Fetch API problems with setInterval()
Fetch API problems with setInterval()

Time:01-29

I want to use setInterval () to run this JS Fetch script every 2 seconds as my server content changes frequently for art.txt. I can't get anything to work. Thank you for your help.

<!DOCTYPE html>
<html>
<body>
<p id="kdkz"></p>
<script>

let file = "art.txt"

fetch (file)
.then(x => x.text())
.then(y => document.getElementById("kdkz").innerHTML = y);
setInterval(fetch(), 2000);

</script>
</body>
</html>

CodePudding user response:

You should wrap the fetch into a function.

<!DOCTYPE html>
<html>
  <body>
    <p id="kdkz"></p>
    <script>
      let file = 'art.txt';

      const handleFetch = () => {
        fetch(file)
          .then((x) => x.text())
          .then((y) => (document.getElementById('kdkz').innerHTML = y));
      };

      setInterval(() => handleFetch(), 2000);
    </script>
  </body>
</html>
  •  Tags:  
  • Related