停止javascript无限循环onmouseout

Stop javascript infinite loop onmouseout?

本文关键字:onmouseout 无限循环 javascript 停止      更新时间:2023-09-26

我正在"动画"一个悬浮的精灵。问题是我不知道如何在mouseout上停止循环。所以基本上在鼠标悬停之后,精灵会无限移动。

$("#explore").hover(function () { // Listen for hover
var number2 = 0;
setInterval(function() { // Animate sprite changing it's margin
        switch (number2) {
        case 0: 
        sprite2.style.marginLeft=-32;
        number2++;
        break;
        case 1: 
        sprite2.style.marginLeft=-64;
        number2++;
        break;
        case 2: 
        sprite2.style.marginLeft=0;
        number2 = 0;
    }
}, 120);
},function () {
        sprite2.style.marginLeft=0;
});

我如何使它停止在mouseout?还有,是否有最短(更少的代码)的版本来做同样的事情?在我的印象中,我在循环中浪费了很多行。由于


我尝试了这个基于Pointy注释,但不知道如何正确地做:

var number2 = 0;
var timer = setInterval(function() {
        switch (number2) {
        case 0: 
        sprite2.style.marginLeft=-32;
        number2++;
        break;
        case 1: 
        sprite2.style.marginLeft=-64;
        number2++;
        break;
        case 2: 
        sprite2.style.marginLeft=0;
        number2 = 0;
    }
}, 120);
},function () {
    clearInterval(timer);
});

试试这个

$("#explore").hover(function () { // Listen for hover
var number2 = 0;
$(this).data("hovertimer", setInterval(function() { // Animate sprite changing it's margin
        switch (number2) {
        case 0: 
        sprite2.style.marginLeft=-32;
        number2++;
        break;
        case 1: 
        sprite2.style.marginLeft=-64;
        number2++;
        break;
        case 2: 
        sprite2.style.marginLeft=0;
        number2 = 0;
    }
}, 120));
},function () {
        clearTimeout($(this).data("hovertimer"));
        sprite2.style.marginLeft=0;
});

当您调用"setInterval()"时,将它返回的值保存在某个变量中(或在".data()"属性中)。然后,当你想要停止动画时,将该值传递给"clearInterval()"。

var timer = setInterval(function() { ...
// later ...
clearInterval(timer);

我知道这是一个旧的帖子,但有一个轻量级的插件(我碰巧是开发人员),它被称为"spriteOnHover jQuery plugin",它的工作为动画精灵悬停和鼠标事件,并有参数做几乎所有的技巧。当然它是开源的。jQuery spriteOnHover