I’m trying to improve this plugin adding events handlers to toggle play/stop when you mouseenter/mouseleave on a slide. I’ve seen loads of people having the same problem with the js function setTimeout and clearTimeout, and I’m having a trouble too. This is what I have
var autoplay;
container.mouseenter(function(){
autoplay = setTimeout(function() {
slide('next');
}, config.auto);
console.log('play');
}).mouseleave(function(){
clearTimeout(autoplay);
console.log('stop');
});
The slides start to show up in mouseenter, but don’t stop when I do the mouseleave. What I am doing wrong? It is a scope misunderstanding? I don’t know what I’m missing.
I can’t see any reason why your code wouldn’t work provided
containerhas exactly one matched element in it (working example). If there’s any chance that it may match more than one element, then you’ll have multiple elements sharing the sameautoplaytimer handle and it’ll become a bit of a mess. If so, usedatato store the handle actually on the element the mouse event occurred on:Live example
Separately, it’s probably worth clearing
autoplay(wherever you store it) when the timer fires, so you know you don’t have a pending timer.