Question

It seems that everyone has a few problems with clearInterval. I have built a slider that allows people to hover a click on arrows. The banner also rotates ever few seconds. I want to be able to have the auto-rotate turn off after someone clicks on one of the arrows.

Here's my code:

$(function(){
    var intvl = 0;
    intvl = setInterval(heroTransitionNext, 2000);
    $('.rightArrow').click(function(){
       window.clearInterval(intvl);
    });
});

EDIT:

Here is the function it is calling:

function heroTransitionNext() {
    $('.HP-hero li').filter(':visible').fadeOut('normal', function () {
        if ($(this).next().length != 0) {
            activeZone = parseInt(activeZone) + 1;
            $(this).next().fadeIn('normal', heroNavHighlight(activeZone));
        } else {
            activeZone = 1;
            $('.HP-hero li:first-child').fadeIn('normal', heroNavHighlight(activeZone));
        }
        $(this).hide();
    });
};
Was it helpful?

Solution

To stop the animation you can use jquery's .stop() but not sure whether it'll solve the problem or not that you are facing (didn't visualize) but you can give it a try

$('.HP-hero li').stop(1,1); // or try $('.HP-hero li').stop()
window.clearInterval(intvl);

As say2joe said that clearInterval will just stop the function from invoking next time but it won't clear the current queue (he is right) so in that case stop could be used.

About Stop.

OTHER TIPS

Depending on how much work your heroTransitionNext function is doing, it may still be executing even though the interval is cleared -- in other words, clearing the interval will stop the function from being invoked -- but, any instance of the function(s) executing in memory will continue to execute until finished.

To be more clear, here's a use case (you can check this out yourself by using a profiler in Firebug or Developer Tools):

heroTransitionNext execution time is 2.1 seconds. clearInterval is invoked 6.1 seconds after setInterval is invoked. At 6.1 seconds, heroTransitionNext has been invoked four times. The first three executions have completed, however, the fourth will not complete until it finishes executing (at 8.1 seconds since setInterval was called). Note: In this use case, each successive invokation will execute while the last invokation's execution is still continuing (for 100 more ms) -- in other words, you'll have execution overlap from 2 to 2.1, 4 to 4.1, and 6 to 6.1 second intervals.

If the function takes longer to execute than the interval set, use a recursive function with setTimeout(). The following link will give you a good example.

Also, a good reference for explanation is https://developer.mozilla.org/en/DOM/window.setInterval.

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