Search code examples
javascriptsetintervalclearinterval

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.


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.