如何在html中停止更改照片

时间:2016-03-20 07:37:10

标签: javascript html setinterval

我想帮助这个代码执行在三次之后停止?

我有三张照片,想要改变三次并停止

xmlstarlet
你可以帮帮我吗?

2 个答案:

答案 0 :(得分:1)

使用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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

此问题已解决here(已接受答案,第二个代码块)!