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.
The
firstIntervalis creating multiplesecondIntervalsEach time the
firstIntervalfires, it creates its ownsecondInterval. Only one of thesecondIntervals gets cleared.To fix this, change the first one to a
setTimeout, so it only fires once.