Search code examples
functionhoversetintervalmouseovermouseout

jQuery setInterval on mouseover


I have a problem that i will not be able to solve by myself. I want to show a countdown timer once they hover over a photo. It works the first time you hover. If you move the mouse and hover again it will just be weird numbers jumping. I hope someone can help me with this!

Best Regards,

Tassilo

 <script>

$('.Photo').on({

    'mouseover': function () {

var timer = 5;  

var interval = setInterval(function() {
    timer--;
    $('.timer').text(timer);
    if (timer === 0) clearInterval(interval);
}, 1000);  

    },      
'mouseout' : function () {
        clearTimeout(timer);   
    }       
});
</script>

Solution

  • I think it's because the timer variable is declared locally inside the mouseover(), and you're trying to clear it inside the mouseout(). Try placing it outside the $('.Photo').on({ });

    Additionally, place your interval variable outside so you can clear it in your mouseout() function.

    <script>
    
        var interval;
        var timer = 5;
    
        $('.photo').on({
    
            'mouseover': function () {
    
                interval = setInterval(function() {
                    timer--;
                    $('.timer').text(timer);
                    if (timer === 0) clearInterval(interval);
    
                }, 1000);  
    
            },
    
           'mouseout' : function () {
               clearInterval(interval);
               timer = 5;
            }       
        });
    </script>