I have a function called testimonials() that basically cycles through a set of divs, whereas it animates a div in, animates it out and animates the next one in.
Now, I wanted to make it stop on the current DIV once the mouse is on it, otherwise known as hovering it. And I’ve made it work using a code I got from another post in this site, I was just wondering if someone could explain it to me because I’m a little new to jQuery and I really want to understand why it is working.
The code is the following:
function testimonials() {
//function here
}
//to stop on hover
var timerId = null;
function startRotation() {
if (timerId) {
return;
}
timerId = setInterval('testimonials()', 5000);
}
function stopRotation() {
if (!timerId) {
return;
}
clearInterval(timerId);
timerId = null;
}
$(function () {
startRotation();
$('.testimonials').hover(stopRotation, startRotation);
});
So how this is working…let’s break it down piece by piece.
.hover(func1, func2)is a shortcut for.mouseenter(func1).mouseleave(func2), meaning the first function executes when your mouse enters the element, the second when it leaves.First function, when the mouse enters:
This is stopping the interval previously set via
setInterval()from running anymore, killing the current loop viaclearInterval()and clearing thetimerIdvariable, so thestartRotationfunction restarts the loop when it’s ready to (onmouseleave).Second function, when the mouse leaves:
This re-starts the loop by starting a timer to run
testimonials()every 5 seconds, but only if there isn’t a timer already running (by checkin iftimerIdis set). It does this viasetInterval().One change I would make, never pass a string into
setInterval()orsetTimeout(), this runs aneval()internally. Instead just call the function reference directly, like this: