In this example, I've shown how to pause and restart the animation on a hover()
event. This also restarts the animation exactly where it left off.
$(function () {
var $looped = $('li');
var timeOut;
var index = 0;
function _loop(idx) {
$looped.removeClass('current').eq(idx).addClass('current');
timeOut = setTimeout(function () {
index = (idx + 1) % $looped.length;
_loop(index);
}, 1000);
};
_loop(index);
$("ul").hover(function () {
window.clearTimeout(timeOut);
}, function () {
_loop(index);
});
$("li").hover(function () {
$("li").removeClass("current");
$(this).addClass("current");
}, function () {
$("li").removeClass("current");
});
});
There's a few key points.
First - I assign a function-scoped variable (not global) within the anonymous function that tracks the timeout function. This allows me to clear it at a later time within that function. It's typically a bad idea to clutter up the global namespace unnecessarily.
Second - I changed the mouseenter()
function to a hover()
function, which accepts two functions as parameters, one for the mouse over, and one for the mouse out events.
Third - I added in a variable called index
which is going to keep track of the index for us throughout the function. This allows the loop to resume exactly where it left off when the mouse is no longer over the element.
See the Fiddle HERE