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 () {
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