2

I'm very new to coding so bear with me on this one.

I'm currently creating an Image gallery that has an AutoPlay button feature (this I've managed to create) however I can't seem to figure out a way to stop it without refreshing the page. Ideally I'd like to stop it using another separate function that calls on my first image when clicking it.

//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;
Mathlight
  • 6,436
  • 17
  • 62
  • 107

2 Answers2

4

You can clear the interval, asigning first to a global variable:

// 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';
}

Good luck!

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
0

You can't stop execution of one function from anywhere. But if you are using setInterval() then you can stop/clear it with clearInterval().

clearInterval(interval_ID);

Full code:

//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;
Manwal
  • 23,450
  • 12
  • 63
  • 93
  • Thank you so much! this did it for me. I had actually tried this method earlier, I just didn't name things properly. – Camille Rees Aug 30 '15 at 12:28