javascriptsetintervalmouseoverclearintervalmouseleave

Javascript start and repeat function upon mouseover & stop repeat upon mouseleave


I am successfully starting an animation upon mouseover, but cannot manage to stop it upon mouseleave:

Start animation:

var executed = false; // to execute only once on repeat hover
var startslider = {};

$('#imgBx').mouseover(function(){

if (!executed) { 
    var startslider = setInterval(function(){
    executed = true;  
    rotateSlide();
    }, 1000);
} // end if executed

}); // end mouseover

Stop animation:

$('#imgBx').mouseleave(function(){
    clearInterval(startslider);
});

Solution

  • You are re-declaring the global variable 'startslider'.

    Remove the var from the variable in the mouseover event listener.

     startslider = setInterval(function(){