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

why does my clearInterval not clear the interval? – JavaScript

I got two intervals, one is inside the other:

function start(start) {

    if (start) {
        firstInterval = setInterval(function () {

            console.log("firstInterval called")
            secondInterval = setInterval(function(){

                clearInterval(secondInterval)
                secondInterval = null
                console.log("secondInterval called")
            },1000)


        }, 1000)

    }else{

        clearInterval(firstInterval)
        firstInterval = null

        clearInterval(secondInterval)
        secondInterval = null

    }
}

the else block gets called when I press a "stop" button, the "firstInterval" gets cleared but the "secondInterval" keeps on logging "secondInterval called"

Why does this happen and how can I prevent this.

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 :

The firstInterval is creating multiple secondIntervals

Each time the firstInterval fires, it creates its own secondInterval. Only one of the secondIntervals gets cleared.

To fix this, change the first one to a setTimeout, so it only fires once.

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