user5687432
user5687432

Reputation:

Javascript - Stop Slideshow timeout

I have a slideshow that displays one image each second

But I wanted a "stop button" in order to.....stop the carousel XD I'm working on it but I separated the both functions (one for carousel, one for buttons).

Here is the HTML

<div id="gallerie2">
    <img id="first2" src="http://lorempicsum.com/futurama/150/150/2"><br/>
    <div id="vignette">
        <img class="second2" src="http://lorempicsum.com/futurama/150/150/6">
        <img class="second2" src="http://lorempicsum.com/futurama/150/150/4">
        <img class="second2" src="http://lorempicsum.com/futurama/150/150/3">
        <img class="second2" src="http://lorempicsum.com/simpsons/150/150/2">
        <img class="second2" src="http://lorempicsum.com/simpsons/150/150/1">
        <img class="second2" src="http://lorempicsum.com/simpsons/150/150/4">
    </div>
</div>

<div id="controlSlideShow">
    <button id="start">Start</button>
    <button id="stop">Stop</button>
</div>     

Here is the Javascript for the slideshow (it works perfectly, that's not the problem)

var index = 0;
    setInterval(function nextSlide(){
        var slides = document.getElementsByClassName("second2");
        var firstSlide = document.getElementById("first2");
        firstSlide.src = slides[index].src;
        index++;
        if(index == slides.length){
            index = 0;   
        }
    }, 1000);

Then here is the Javascript for buttons where the problem is

    document.getElementById("controlSlideShow").addEventListener('click', controlSlideShow);
    function controlSlideShow(e){
        switch(e.target.id){
            case 'stop':
                console.log("clickStop");
                clearTimeout(nextSlide);
            break;
            case 'start': console.log("start");
            break;   
        }
    }

I'm working on those buttons but I can't call the nextSlide() function a clearTimeout() in order to stop the slideshow.

Thank you for taking time to my problem. Can you explain me after resolving ? I really want where is(are) my mistake(s), not just take the solution. =)

Here is the jsFiddle : https://jsfiddle.net/k3g19dbo/

Upvotes: 0

Views: 492

Answers (1)

trincot
trincot

Reputation: 350202

The argument you need to pass to clearInterval (not clearTimeout) is not the name of the function you passed to setInterval, but the value that setInterval returns. So do this:

var timerId = setInterval(function nextSlide(){
     // ... etc
}, 1000);
// ...
clearInterval(timerId);
// ...

NB: clearTimeout would also work in most browsers, but it just makes more sense to call clearInterval when you used setInterval, and clearTimeout when you used setTimeout.

Upvotes: 1

Related Questions