user5281718
user5281718

Reputation:

How to stop one function using another

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;

Upvotes: 2

Views: 80

Answers (2)

Manwal
Manwal

Reputation: 23836

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;

Upvotes: 0

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

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!

Upvotes: 4

Related Questions