Change image in HTML page every few seconds

As I posted in the comment you don’t need to use both setTimeout() and setInterval(), moreover you have a syntax error too (the one extra }). Correct your code like this:

(edited to add two functions to force the next/previous image to be shown)

<!DOCTYPE html>

<html>
   <head>
      <title>change picture</title>
      <script type = "text/javascript">
          function displayNextImage() {
              x = (x === images.length - 1) ? 0 : x + 1;
              document.getElementById("img").src = images[x];
          }

          function displayPreviousImage() {
              x = (x <= 0) ? images.length - 1 : x - 1;
              document.getElementById("img").src = images[x];
          }

          function startTimer() {
              setInterval(displayNextImage, 3000);
          }

          var images = [], x = -1;
          images[0] = "image1.jpg";
          images[1] = "image2.jpg";
          images[2] = "image3.jpg";
      </script>
   </head>

   <body onload = "startTimer()">
       <img id="img" src="https://stackoverflow.com/questions/13975891/startpicture.jpg"/>
       <button type="button" onclick="displayPreviousImage()">Previous</button>
       <button type="button" onclick="displayNextImage()">Next</button>
   </body>
</html>

Leave a Comment