Pausing a function “onClick”

有些话、适合烂在心里 提交于 2019-12-13 07:07:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!