Skip to content Skip to sidebar Skip to footer

Pause Button For Javascript Slideshow

I am trying to create a pause button for a JavaScript slideshow that is an infinite loop that displays random images. The error console doesn't throw any errors. The slideshow star

Solution 1:

A few problems:

First, whenever you call keeprollin(), it starts a loop. The loop goes

keeprollin()
magic()
keeprollin()
margin()
...infinite

You never stop this chain once it starts. You had the right idea by setting var t as the value returned by setTimeout, but setting t to the value "stopped" doesn't stop this cycle. You need to use clearTimeout(t) to stop the cycle.

Second, the scope of your var t is off. In a function, var t will tie the scope of the variable to the function, which won't be accessible in any other function. If you drop the var line, this will tie the value to the window, and the t variable will be properly set wherever you reference it.

Third, don't use the length of the string to determine what you want to do, just compare strings. switcha.getAttribute("value").length==9 should be switcha.getAttribute("value") == 'Slideshow'

Fourth, don't name your functions or variables weird or funny names. You'll save yourself and others headache in the future if you are descriptive in your naming. It will make your code much easier to read.

... done ranting now :)

Solution 2:

(function() {
    var t;

    functionletsslide() {
        var switcha = document.getElementById("SlideShow");
        if (switcha.value === "Slideshow") {
            switcha.value = "Pause";
            t = setTimeout(magic, 2000);
        }
        if (switcha.value === "Pause") {
            switcha.value = "Slideshow";
            clearTimeout(t);
        }
    }

    window.letsslide = letsslide;

    functionmagic() {
        var dazp = Math.ceil(Math.random() * 35);
        document.getElementById('bigpic').src = "images/" + dazp + ".jpg";
        t = setTimeout(magic, 2000);
    }

})();

Refactored so that it works. Added a closure so t is not global anymore.

Solution 3:

var t;
functionstartSlideshow() {
     t = setInterval(magic, 2000);
}
functionletsslide(){
     var switcha = document.getElementById("SlideShow");
     if (switcha.getAttribute("value").length == 9) {
           startSlideshow();
           switcha.setAttribute("value", "Pause");
     }
     if (switcha.getAttribute("value").length == 5) {
           clearTimeout(t);
           switcha.value = "Slideshow";
     }
}
functionmagic(){
     var dazp = Math.ceil(Math.random() * 35);
     document.getElementById('bigpic').setAttribute("src", "images/" + dazp + ".jpg");
}

Is probably more what you want.

Post a Comment for "Pause Button For Javascript Slideshow"