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

三世轮回 提交于 2019-11-30 16:03:20

问题


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.


回答1:


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();
});


来源:https://stackoverflow.com/questions/10442452/setinterval-and-clearinterval-when-cleared-does-not-animate-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!