Javascript - 没有重复的图像

时间:2016-01-25 18:47:54

标签: javascript

我在JavaScript中使用此代码,此图像1-6仍在重复。但我希望当它在6时它停止而不重复。我该怎么办?

<script>
     function displayNextImage2() {
              y = (y === images2.length - 1) ? 0 : y + 1;
              document.getElementById("img2").src = images2[y];
          }

          function displayPreviousImage2() {
              y = (y <= 0) ? images2.length - 1 : y - 1;
              document.getElementById("img2").src = images2[y];
          }

          function startTimer2() {
              setInterval(displayNextImage2, 5000);
          }

          var images2 = [], y = 0;
          images2[0] = "images/one.PNG";
          images2[1] = "images/two.PNG";
          images2[2] = "images/three.PNG";
          images2[3] = "images/four.PNG";
          images2[4] = "images/five.PNG";
          images2[5] = "images/six.PNG";
</script>

感谢每一个答案。

1 个答案:

答案 0 :(得分:0)

displayNextImage2方法更改为

function displayNextImage2() 
{
  if ( y <= images2.length - 1 )
  {
     document.getElementById("img2").src = images2[y];
     y++;
     clearInterval(timer2);
  }
}

确保您也清除间隔,因此您需要保留它的参考

var timer2 = "";
function startTimer2() 
{
     timer2 =   setInterval(displayNextImage2, 5000);
}

它到达最后一张图像后不会重复