user803592
user803592

Reputation: 51

setTimeout, clearTimeout jQuery

I have an existing function in a content slider script, that sets a timeout for the next slide to animate in. I would like to stop the animation on mouseover (I commented my addition to the script). What am I doing wrong? Thanks for your help.

    function autoSlide() {
        if (navClicks == 0 || !settings.autoSlideStopWhenClicked) {
            if (currentPanel == panelCount) {
                var offset = 0;
                currentPanel = 1;
            } else {
                var offset = - (panelWidth*currentPanel);
                currentPanel += 1;
            };
            alterPanelHeight(currentPanel - 1);
            // Switch the current tab:
            slider.siblings('.coda-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (currentPanel - 1) + ') a').addClass('current');
            // Slide:



            $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);

            setTimeout(autoSlide,settings.autoSlideInterval); 

     // this is my addition to try to stop the animation:               
            $('.panel-container', slider).mouseover(function(){
            //alert("hi");
               clearTimeout(autoSlide);

            }).mouseleave(function(){

               setTimeout(autoSlide,settings.autoSlideInterval);

            });
    // end of my addition          

        };
    };

Upvotes: 1

Views: 3182

Answers (2)

Endophage
Endophage

Reputation: 21473

autoSlide isn't the timeout, it's your function name so you can't clear the timeout on it. setTimeout returns a reference to the timeout which you need to capture and call clearTimeout on that. See below code:

var slideTimeout = setTimeout(autoSlide,settings.autoSlideInterval); 


$('.panel-container', slider).mouseover(function(){
    clearTimeout(slideTimeout);
}).mouseleave(function(){
    slideTimeout = setTimeout(autoSlide,settings.autoSlideInterval);
});

Upvotes: 0

kapa
kapa

Reputation: 78671

clearTimeout() works with the return value of setTimeout() (an ID for the operation), so you should save it when you set it, and use that for the clear.

var x=setTimeout(autoSlide,settings.autoSlideInterval); 
...
clearTimeout(x);

  • MDC on clearTimeout

    window.clearTimeout(timeoutID)

    where timeoutID is the ID of the timeout you wish to clear, as returned by window.setTimeout().

Upvotes: 3

Related Questions