Question

I'm building a custom slider on Javascript , and I want that every time the user clicks on a div of the slider, the slider should stop for X seconds.

My code is:

$(document).ready(function () {
    var ciclo;
    var index_slide = 1;

    function startSlidercicle() {
        ciclo = setInterval( function() {
            // Slider code goes here
        }, 3000); 
    }

    //Here I start the slider animation
    startSlidercicle();

    //When the user clicks on a div called 'slide', stop the cycle and start again the animation cycle
    $('.slide').on('click', function() {
        clearInterval(ciclo);
        setTimeout(startSlidercicle(), 3000);
    });
});

But the problem is that everytime I click and stop the slider, the cycle starts faster and faster. How can I fix it?

Was it helpful?

Solution

Instead of:

clearInterval(ciclo);
setTimeout(startSlidercicle(), 3000);

or:

clearInterval(ciclo);
setTimeout(startSlidercicle, 3000);

I changed the code to be:

clearInterval(ciclo);
startSlidercicle();

And now the slider just works fine. I think that, in the first two proposals, every time I click on the div, a new function is created, "overlapping" over the existing cycle and, thus, it looks like the slider speeds up, but its just one cycle starting over another.

OTHER TIPS

You need to change this:

clearInterval(ciclo);
setTimeout(startSlidercicle(), 3000);

to this:

clearInterval(ciclo);
setTimeout(startSlidercicle, 3000);

In your existing code, you are calling startSlidercirle immediately and it is not waiting until the setTimeout() fires because you have the () after the function name. That means to execute it immediately and pass the result of executing that to setTimeout(). You want to just pass the function reference to setTimeout() which is done by just having the name of the function with no () after it. This is a common mistake.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top