如何停止更改 html 中的照片

how can stop change photo in html

我想帮助使这段代码执行仅执行 3 次就停止吗?

我有三张照片,想换三次就停

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

你能帮帮我吗?

使用clearInterval停止setInteval函数。

<!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] = "http://i.stack.imgur.com/0qVbB.jpg";
      images[1] = "http://i.stack.imgur.com/Z4D6Z.jpg";
      images[2] = "http://i.stack.imgur.com/JbyGx.jpg";
    </script>
  </head>

  <body onload = "startTimer()">
    <img id="img" src="http://i.stack.imgur.com/0qVbB.jpg"/>
    <button type="button" onclick="displayPreviousImage()">Previous</button>
    <button type="button" onclick="displayNextImage()">Next</button>
  </body>
</html>