开发者

Stop javascript infinite loop onmouseout?

开发者 https://www.devze.com 2023-04-03 03:13 出处:网络
I\'m \"animating\" an sprite on hover. The problem is that I don\'t know how to stop the loop onmouseout. So basically after hovering the mouse the sprite keeps moving indefinitely.

I'm "animating" an sprite on hover. The problem is that I don't know how to stop the loop onmouseout. So basically after hovering the mouse the sprite keeps moving indefinitely.

$("#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 () {
        开发者_JAVA技巧sprite2.style.marginLeft=0;
});

How do I make it stop onmouseout? Also is there a shortest (less code) version to do the same thing? I'm under the impression that I'm wasting a lot of lines on my loop. Thanks


I tried this based on Pointy comment, but can't figure out how to do it properly:

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


Try this

$("#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;
});


When you call "setInterval()", save the value it returns in a variable someplace (or in a ".data()" property). Then, when you want to stop the animation, pass that value to "clearInterval()".

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

// later ...

clearInterval(timer);


I know this is an old post, but there is a lightweight plugin (that I happen to be the developer) which is called "spriteOnHover jQuery Plugin", it works for animating sprites on hover and mouse events and have parameters that do almost every trick. Of course it's open source. jQuery spriteOnHover

0

精彩评论

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