1

I want to help to make this code execution stops after just three times for?

I have three photos and want to change for three times and stop

<!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="1.jpg"/>
       <button type="button" onclick="displayPreviousImage()">Previous</button>
       <button type="button" onclick="displayNextImage()">Next</button>
   </body>
</html>

can you help me?

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Mona Ahmad
  • 33
  • 6
  • Try to add (all) relevant tags when asking a question; that way, a lot more people will be able to reach -and thus try and help- you. HTML isn't really what this question is about, it should be javascript. Good luck! – SND Mar 20 '16 at 07:47
  • You have to use `clearInterval` method, refer [w3schools.com Window clearInterval() Method](http://www.w3schools.com/jsref/met_win_clearinterval.asp) – Techie Mar 20 '16 at 08:15

1 Answers1

1

Use clearInterval to stop the setInteval function.

<!DOCTYPE html>

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

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

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

      var images = [], x = -1;
      images[0] = "https://i.stack.imgur.com/0qVbB.jpg";
      images[1] = "https://i.stack.imgur.com/Z4D6Z.jpg";
      images[2] = "https://i.stack.imgur.com/JbyGx.jpg";
    </script>
  </head>

  <body onload = "startTimer()">
    <img id="img" src="https://i.stack.imgur.com/0qVbB.jpg"/>
    <button type="button" onclick="displayPreviousImage()">Previous</button>
    <button type="button" onclick="displayNextImage()">Next</button>
  </body>
</html>
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135