setinterval() and clearinterval() - when cleared, does not animate automatically

Kasper Lewau picture Kasper Lewau · May 4, 2012 · Viewed 46.5k times · Source

So I'm trying to build an animating background image which will cycle through an array of images.

The idea is also that when you click any navigation element on the page, the cycle will pause.

When you click on the home button, the cycle is to start up again (from the current image).

This works in it's current state, however the cycle is not automatic upon re-firing it, instead you have to press the home button for each fade/slide/whatever.

The script is as follows:

$(document).ready(function(){

    var imgArr = new Array(
        'img/slides/slide1.jpg',
        'img/slides/slide2.jpg',
        'img/slides/slide3.jpg');

    var preloadArr = new Array();
    var i;


    // Preload
    for(i=0; i < imgArr.length; i++){
        preloadArr[i] = new Image();
        preloadArr[i].src = imgArr[i];
    }

    var currImg = 1;
    var IntID = setInterval(startSlider, 4000);

    // Image Rotator

    function startSlider(){
        $('.mainbg').animate({opacity: 0}, 1200, "easeInOutExpo", function(){
            $(this).css('background','url(' + preloadArr[currImg++%preloadArr.length].src + ') no-repeat center center fixed');
            $(this).css({'background-size': 'cover' , '-webkit-background-size': 'cover' , '-moz-background-size': 'cover' , '-o-background-size': 'cover' ,});
            }).animate({opacity: 1}, 1200, "easeInOutExpo");
        }

    function stopSlider() {
        clearInterval(IntID);
    }

    $(".topnav ul li a").click(stopSlider);

    $("#home").click(startSlider);
});

If someone could please point me in the correct direction with this, it'd be greatly appreciated! Best regards, Kasper.

Answer

Matthew Nie picture Matthew Nie · May 4, 2012

This should do it for you.

var IntID = setTimer();

function setTimer(){
     i = setInterval(startSlider, 4000);
     return i;
}

function stopSlider() {
    clearInterval(IntID);
}

//Restart Timer
// Option 1 make a restartSlider function and call it
$("#home").click(restartSlider);
function restartSlider(){
      IntID = setTimer();
}

//Option 2 create an anonymous function only for that click event.
$("#home").click(function(){
     IntID = setTimer();
});