why does my clearInterval not clear the interval? - JavaScript

43 Views Asked by At

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.

1

There are 1 best solutions below

2
ProfDFrancis On BEST ANSWER

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.