Jeff
Jeff

Reputation: 2862

clear interval on mouseout

I'm trying to get a simple image cycle (no transitions) to work where images begin to cycle on mouseover, and stop cycling on mouseout. This works, except for stopping on mouseout. I'm having a hard time figuring out how to clear the interval:

var itemInterval = 750; 
var numberOfItems = $('.portrait img').length;          
//set current item
var currentItem = 0;             
//show first item
$('.pimg').eq(currentItem).show();           

$('.portrait').hover(function() {                       
    //loop through the items
    var infiniteLoop = setInterval(function(){
        $('.pimg').eq(currentItem).hide();
        if(currentItem == numberOfItems -1){
            currentItem = 0;
        }else{
            currentItem++;
        }
        $('.pimg').eq(currentItem).show();
    }, itemInterval);
},
function() {
    clearInterval(infiniteLoop);
});

How can I get that second-to-last line working?

Edit: fixed a couple of non-code typos

Upvotes: 0

Views: 1895

Answers (3)

Jose Faeti
Jose Faeti

Reputation: 12302

you declared infiniteLoop inside a function, which is not avaiable inside the other anonimous function where you are calling it. Just declare that variable outside both functions.

Upvotes: 2

Declan Cook
Declan Cook

Reputation: 6126

I think you have a scope issue. try

var itemInterval = 750; 
var numberOfItems = $('.portrait img').length; 
var infiniteLoop = null;      
//set current item
var currentItem = 0;             
//show first item
$('.pimg').eq(currentItem).show();           

$('.portrait').hover(function() {                       
    //loop through the items
    infiniteLoop = setInterval(function(){
        $('.pimg').eq(currentItem).hide();
        if(currentItem == numberOfItems -1){
            currentItem = 0;
        }else{
            currentItem++;
        }
        $('.pimg').eq(currentItem).show();
    }, itemInterval);
},
function() {
    clearInterval(infiniteLoop);
});

Upvotes: 1

Niklas
Niklas

Reputation: 30002

Define var infiniteLoop outside of the function, and inside the function set the timeout as infiniteLoop = setInterval... (without var). Full code:

var infiniteLoop;
$('.portrait').hover(function() {                       
    //loop through the items
    infiniteLoop = setInterval(function(){
        $('.pimg').eq(currentItem).hide();
        if(currentItem == numberOfItems -1){
            currentItem = 0;
        }else{
            currentItem++;
        }
        $('.pimg').eq(currentItem).show();
    }, itemInterval);
},
function() {
    clearInterval(infiniteLoop);
});

Upvotes: 3

Related Questions