一次多个setIntervals

时间:2017-08-09 18:23:52

标签: javascript

我目前正在使用JavaScript,并且正在使用setInterval函数。我有一个函数,它使用两个setIntervals函数在两个不同的图片之间切换。现在我尝试使用clearInterval让它停止。

这是我的职能:



function changePic(){
  document.puppy.src = "puppy2.jpg";
}

function changePicBack(){
  document.puppy.src = "puppy1.jpg";
}

function changeBetween(){
  var puppyChange = setInterval(changePic, 2000);
  var puppyChange2 = setInterval(changePicBack, 3000);
 }




我通过这样的按钮执行此操作:

<input type="button" value="Change Between" onclick="changeBetween();" />

有没有一种简单的方法可以创建一个clearInterval函数来停止两个设置间隔函数并让它从一个按钮运行?

1 个答案:

答案 0 :(得分:0)

(function() {

  var puppy = document.getElementById("puppy"), // Collect your image element
    button = document.getElementById("button"), // Collect your button element
    images = [
      "http://placehold.it/100x100/0bf",
      "http://placehold.it/100x100/fb0",
      "http://placehold.it/100x100/f0b"
      // Need more? add more
    ],
    tot = images.length, // how many puppies we have?
    c = 0, // current image index counter
    itv, // the interval
    isPlaying = false;

  function anim() { // Not exactly an anim.. but I'm sure you'll rock this out!
    c = ++c % tot; // Increment counter and reset to 0 if exceeds tot
    puppy.src = images[c]; // Use the image matching current index
  }

  function play() {
    isPlaying = true;
    itv = setInterval(anim, 2000);
    button.value = "Pause";
  }

  function stop() {
    isPlaying = false;
    clearInterval(itv);
    button.value = "Play";
  }

  button.addEventListener("click", () => {
    if (isPlaying) {
      stop();
    } else {
      play();
    }
  });

}());
<img id="puppy" src="http://placehold.it/100x100/0bf">
<input id="button" type="button" value="Play" />