我对编码非常陌生,所以请耐心等待。
我目前正在创建一个具有自动播放按钮功能的图片库(我已设法创建)但是我似乎无法找到一种方法来停止它而不刷新页面。理想情况下,我想使用另一个单独的函数来停止它,该函数在单击时调用我的第一个图像。
//Autoplay button//
function autoPlay() {
(function () {
var gallery = document.getElementById('gallery'); //Identifying image ID
var delayInSeconds = 60; // setting number of seconds to delay images
var images = ["Images/1.JPG", "Images/2.JPG", "Images/3.JPG", "Images/4.JPG", "Images/5.JPG", "Images/6.JPG", ]; // list of image names
var num = 0;
var changeImage = function () {
var len = images.length;
gallery.src = images[num++];
if (num === len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 50);
})();
}
document.getElementById("play").onclick = autoPlay;
//Stop button//
function stopButton() {
document.getElementById('gallery').src = 'Images/1.JPG';
}
document.getElementById("stop").onclick = stopButton;
答案 0 :(得分:4)
您可以清除间隔,首先将其作为全局变量:
// your code
window.varInterval = setInterval(changeImage, delayInSeconds * 50);
// your code
function stopButton (){
clearInterval(varInterval); // this is the key
document.getElementById('gallery').src = 'Images/1.JPG';
}
祝你好运!
答案 1 :(得分:0)
您无法从任何地方停止执行一项功能。但是,如果您使用setInterval()
,则可以使用clearInterval()停止/清除它。
clearInterval(interval_ID);
完整代码:
//Autoplay button//
var intervalVar;
function autoPlay() {
(function () {
var gallery = document.getElementById('gallery'); //Identifying image ID
var delayInSeconds = 60; // setting number of seconds to delay images
var images = ["Images/1.JPG", "Images/2.JPG", "Images/3.JPG", "Images/4.JPG", "Images/5.JPG", "Images/6.JPG", ]; // list of image names
var num = 0;
var changeImage = function () {
var len = images.length;
gallery.src = images[num++];
if (num === len) {
num = 0;
}
};
intervalVar = setInterval(changeImage, delayInSeconds * 50);
})();
}
document.getElementById("play").onclick = autoPlay;
//Stop button//
function stopButton() {
clearInterval(intervalVar);
document.getElementById('gallery').src = 'Images/1.JPG';
}
document.getElementById("stop").onclick = stopButton;