I created a gallery with auto-play.
When the gallery STOP it’s animation and we hover the gallery, all works as expected.
But I am getting a strange issue:
While the gallery is animating –> hovering the gallery, the clearTimeout seem not to work correctly and on mouseleave the gallery behave strangely
or it’s happening a strange conflict I cannot understand and resolve. I went back to an other gallery I made a couple of days before fith a similar functionality and I encountered the same issue.
I am missing something crucial here
THE GALLERY IN QUESTION: jsFiddle
var myTimeOut;
/////// ANIMATION /////////////
function animation(cb){
$('#slider').animate({left: '-=600' },800, cb);
}
/////// AUTO SLIDE ////////////
function auto() {
myTimeOut = setTimeout(function() {
animation(function(){
auto();
});
}, 2000);
}
auto();
and how I’m trying to pause it:
///// MOUSE actions //////////
$('#galcontainer').mouseenter( function () {
clearTimeout(myTimeOut);
});
$('#galcontainer').mouseleave( function () {
auto();
});
EDIT
Adding a ‘hover flag’ (as suggested in the answers) works almost great, but a small bug using this solution is visible when ‘fast mouseenter/mouseleave DURING the animation.
A fix to that issue could be adding a $(‘#slider’).stop() at mouseleave. Not a great solution.
What else can I do?
The issue: on
mouseenterduring the animation, the jQuery.animate()callbackcbis already in queue (even if the clearTimeout was called, anotherauto()will be called which will trigger subsequent runs, etc.).Using
setIntervaland leveraging all those callbacks is the key:jsFiddle demo
(Aside notes regarding the original (yet modified) code)
The
directionvariable with"+="and"0-"is unneeded since there’s only one direction, so use acounter = 0indexed, and wrap-around/reset using the Reminder%operator. Also,can be written like:
since
autois already a function.can be used with
.hover(fn1, fn2)method (like in the above example)