开发者

clear interval on mouseout

开发者 https://www.devze.com 2023-03-15 19:43 出处:网络
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

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 == numberOfIt开发者_运维百科ems -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


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消