Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

clearInterval on 'mouseleave'

I’m creating a visual counter in my html using Javascript. At first the counter is ‘0’. On mouseenter it starts counting till 10 (adding +1 every second), and on moueseleave it should reset to 0 again and stop counting, however, when I move the cursor away it only shortly resets to 0, and then keeps counting up to 10 again, starting from the number it stopped at during the mouseleave.

My code looks like this:

let timer = ''

box[4]?.addEventListener('mouseenter', () => {
    let sec = 0
    let timer = setInterval(() => {
        box[4].innerHTML = String(1 + sec)
        sec++
        if(sec === 10){
            clearInterval(timer);
        }       
    }, 1000)   
})  

box[4]?.addEventListener('mouseleave', () => {
    clearInterval(timer)
    box[4].innerHTML = String(0) 
})  

How can I improve it so that on mouseleave the counter becomes 0 again and stops any counting?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to remove the let on let timer inside the mouseenter callback:

let timer = ''

box[4]?.addEventListener('mouseenter', () => {
    let sec = 0
    timer = setInterval(() => {
        box[4].innerHTML = String(1 + sec)
        sec++
        if(sec === 10){
            clearInterval(timer);
        }       
    }, 1000)   
})  

box[4]?.addEventListener('mouseleave', () => {
    clearInterval(timer)
    box[4].innerHTML = String(0) 
})  

The reason is that when you do let timer you are actually populating a new local var called timer and the other var at the top of the code will not be populated. That means your clearInterval inside of the mouseleave handler was not actually canceling anything.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading