2017-08-09 54 views
2

我目前正在倾听JavaScript,并与setInterval函数搞乱。我有一个函数使用两个setIntervals函数在两张不同的图片之间切换。现在我正在尝试使用clearInterval使其停止。多次setIntervals一次

这里是我的功能:

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函数将停止设置间隔函数并使其从按钮运行?

+3

简单。不要使用两个setIntervals。 –

+0

使'puppyChange'和'puppyChange2'全局。 – Li357

+0

@AndrewLi nope。 –

回答

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" />