Ad

How To Restart An Interval Automatically After Cleared It?

Im creating a slideshow which is running automatically when i load the page and it will stop if someone press the prev/next buttons (clearInterval). My problem is that i would like the interval restart after sometime and after it was cleared. I've tried with setTimeout but i think that im doing something wrong.

The slider it's based on an "ul" with images inside, and it will show each one of them by changing the margin of the list. The buttons are placed on the sides of the list with a "data-mov" attribute that it will return "prev" or "next" saving that value in a variable called "dir".

I leave the actual js code that i have, the crucial point is within the "slide" function i believe.

Thank you so much in advance!

( function(){

var slider = $( '.slider' );

var slides = slider.find("li").length;

var actual = 0;

var width = 310;

var interval = setInterval( function(){
    slide( 'next' );
}, 1500 );


function slide( dir, click ){

    if ( click ){
       clearInterval( interval );
    }

    ( dir === "next" ) ? actual -- : actual ++;
    if ( actual > 0 ) {
        actual = ( slides - 1 ) *  -1;
    }else if ( actual <= ( slides * -1  ) ) {
        actual = 0;
    }
    var margin = actual * width;

    slider.animate({
        marginLeft: margin
    }, 450);

}

$('.btn-slide').on('click', function () {

    var dir = $(this).data("mov");
//when the button is pressed we send "true" for the "click" argument
    slide( dir , true);
});

})();
Ad

Answer

Using setTimout is, in my opinion, a completely valid way to restart your slideshow.

You could easily achieve your target by doing this:

     var restartTimer;
     function slide( dir, click ){
        if ( click ){
           clearInterval( interval );
           clearTimeout(restartTimer);

           restartTimer = setTimeout(function () {
               setInterval(slide, 1500, 'next');
           }, 10000); // insert time after which you want it to continue here  
        }

        ( dir === "next" ) ? actual -- : actual ++;
        if ( actual > 0 ) {
            actual = ( slides - 1 ) *  -1;
        }else if ( actual <= ( slides * -1  ) ) {
            actual = 0;
        }
        var margin = actual * width;

        slider.animate({
            marginLeft: margin
        }, 450);
    }

The setTimout will restart it after (in this case) 10000ms, except if you happen to manually move the slider, then the timeout will be reset by the clearTimeout function. And it will wait from that point until the 10000ms have elapsed, after which it will continue again.

Ad
source: stackoverflow.com
Ad