Search code examples
ajaxfetchsetinterval

Fetch API problems with setInterval()


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>

Solution

  • 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>