Search code examples
javascriptjquerysetintervalmaterializeclearinterval

Start animation on mouseleave and stop on mouseenter using setinterval and clearinterval


I'm using the materialize carousel and it's changing slides automatically using setInterval() but i want that this setInterval should stop / pause on hover and restart on unhover.

I have tried using clearinterval but it's not working perfectly.

$(document).ready(function(){

    $('.carousel').carousel(); // Start carousel

    /*  I WAS USING THIS BEFORE JUST FOR CHANGING SLIDES AUTOMATICALLY
    setInterval(function(){
        $('.carousel').carousel('next');
    },2500);
    });
    */

    // THIS IS WHAT IHAVE TRIED

    var myVar;

    function start(){
        var myVar = setInterval(next, 2500);
        function next() {
            $('.carousel').carousel('next');
        }
    }

    function stop() {
        clearInterval(myVar);
        myVar = 0;
    }

    $('.carousel').mouseenter(function(){stop();});
    $('.carousel').mouseleave(function(){start();});

    start();
});

The code is not giving any error.


Solution

  • Replace this line:

    var myVar = setInterval(next, 2500);
    

    with this:

    myVar = setInterval(next, 2500);
    

    You have defined the global variable and in your start function, you are again initializing the variable and assigning the return value of setInterval to it. That means myVar remains unassigned for the remaining code except for the start function. so clearInterval does not work.

    You just need to assign the return value to the global variable myVar and that works for you.