问题
I'm currently working on an image slideshow with 5 buttons (Start, stop, pause, backwards, forwards) My start button loads an autoRun function which starts to play through the images while the backwards/forwards buttons skip/go back an image. I'm wondering how to pause the autoRun function when the pause button is clicked? It doesn't need to resume when clicked again, just needs to pause on the current image it's on. The stop function (once I've finished it) will end the function and go back to the start. Cheers
The HTML:
<button onClick="autoRun()">Start</button>
<button onClick="changeImage(-1); return false;">Previous Image</button>
<button onClick="pause();">pause</button>
<button onClick="changeImage(1); return false;">Next Image</button>
<button onClick="stop();">Stop</button>
</td>
The JavaScript:
var images = ["HGal0.jpg", "HGal1.jpg", "HGal2.jpg", "HGal3.jpg", "HGal4.jpg", "HGal5.jpg", "HGal6.jpg", "HGal7.jpg", "HGal8.jpg", "HGal9.jpg", "HGal10.jpg", "HGal11.jpg", "HGal12.jpg", "HGal13.jpg", "HGal14.jpg", "HGal15.jpg"];
var imageNumber = 0;
var imageLength = images.length - 1;
function changeImage(x) {
imageNumber += x;
// if array has reached end, starts over
if (imageNumber > imageLength) {
imageNumber = 0;
}
if (imageNumber < 0) {
imageNumber = imageLength;
}
document.getElementById("slideshow").src = images[imageNumber];
return false;
}
function autoRun() {
setInterval("changeImage(1)", 2000);
}
回答1:
Set your interval in a variable:
var interval = setInterval("changeImage(1)", 2000);
And clear it with clearInterval():
function pause(){
clearInterval(interval);
}
来源:https://stackoverflow.com/questions/39261749/pausing-a-function-onclick