Nick
Nick

Reputation: 2551

jQuery - Pause & Restart Interval on Hover

There are a few answers to this, but none that I actually understand.

So any help would be great!

My Interval

setInterval(function(){
   nextThumb.trigger("click");
   nextBanner();
   bannerLoop();
}, 1500);

Clear Interval??

$('#thumbs, #banner').hover(function(){
   clearInterval();
});

So when I hover over #thumbs or #banner I want my interval to Pause. When my mouse leaves I want it to resume from where it left off.

Thanks for your time!

Upvotes: 0

Views: 254

Answers (3)

GregL
GregL

Reputation: 38121

First, create two functions to start and stop the interval, and to keep track of the interval ID:

var intervalID;
function startInterval() {
    stopInterval();
    intervalID = setInterval(function(){
        nextThumb.trigger("click");
        nextBanner();
        bannerLoop();
    }, 1500);
}

function stopInterval() {
    if (intervalID)
        clearInterval(intervalID);
    intervalID = null;
}

Then, you want to stop the interval when you hover over and restart it when you mouse out:

$('#thumbs, #banner').hover(stopInterval, startInterval);

Finally, start the interval initially:

startInterval();

Upvotes: 0

BenM
BenM

Reputation: 53198

clearInterval() does not pause an interval; it clears it. You need to reinstate the interval inside the hover intent. This is particularly tricky if you use an anonymous function, so you'd be better to refactor your code as follows:

var intveral = 1500;

function intervalCall()
{
   nextThumb.trigger("click");
   nextBanner();
   bannerLoop();
}

var myInt = setInterval(intervalCalll, interval);

$('#thumbs, #banner').hover(function(){
   clearInterval(myInt);
}, function() {  
    myInt = setInterval(intervalCalll, interval);
});

Upvotes: 1

antyrat
antyrat

Reputation: 27765

You need to assign your setInterval call to some variable:

var myInterval = setInterval(function(){
...

and then pass it to clearInterval function:

clearInterval( myInterval );

To resume it again you need to create new setInterval with assigned myInterval variable that will be visible in your scope.

So your code should be like:

var myInterval;

function createInterval() {
   myInterval = setInterval(function(){
      nextThumb.trigger("click");
      nextBanner();
      bannerLoop();
   }, 1500);
}

createInterval();

$('#thumbs, #banner').hover(function(){
   clearInterval(myInterval);
}, function() {
   createInterval();
});

Upvotes: 3

Related Questions