I am using setInterval to recall a function every 2 seconds and stop it using a button which clears the interval timer but I found out that setInterval timer id never goes back down, it only goes back down when I refresh my browser page and if I don’t, the id number just keeps increases, so something like this:
I click a button, setInterval starts, and the timer id is 4,
I click a button to CLEAR it, the setInterval stops,
I click START button again and the timer id is now 5,
I click a button to CLEAR it, the setInterval stops,
I click START button again and the timer id is now 6,
is this an expected behavior? even after I clear the setInterval timer( using clearIntercal() ). Am I missing something? is there a function I needs to call to reset the timer id back to smaller number?
I created something simple to show the problem:
JS
const btnElStart = document.querySelector(".startBtn");
const btnElClear = document.querySelector(".clearBtn");
let timer = 0;
btnElStart.addEventListener('click',()=>{
clearInterval(timer);
btnElStart.disabled = true;
timer = setInterval(() => {
console.log('Timer id: ',timer);
}, 1000);
});
btnElClear.addEventListener('click',()=>{
clearInterval(timer);
btnElStart.disabled = false;
console.log('Cleared timer id: ', timer);
});
HTML
<body>
<div class="container">
<button class="startBtn">Start</button>
<button class="clearBtn">Clear</button>
</div>
<script src="./script.js"></script>
</body>