清除鼠标时间间隔

时间:2011-06-27 08:43:19

标签: jquery mouseover setinterval

我正在尝试获得一个简单的图像循环(无过渡),以便在鼠标悬停时图像开始循环,并在mouseout上停止循环。这有效,除了停止鼠标输出。我很难弄清楚如何清除间隔:

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

如何让倒数第二行工作?

编辑:修复了一些非代码错别字

3 个答案:

答案 0 :(得分:3)

在函数外部定义var infiniteLoop,在函数内部将超时设置为infiniteLoop = setInterval...(不含var)。完整代码:

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

答案 1 :(得分:2)

你在一个函数中声明了无限循环,这在你调用它的另一个匿名函数中是不可用的。只需在两个函数之外声明该变量。

答案 2 :(得分:1)

我认为你有一个范围问题。尝试

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);
});
相关问题