setInterval timer id reset

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>

I think that’s the normal behaviour in chrome at least.
Try it out in your console - it doesn’t matter as you don’t need the id for anything else than to clear the interval.

1 Like

I’m not sure why you want the timer ID to go back down to a smaller number. Imagine you’d set up three intervals instead of just one. Then you want to clear two of them. Then you add four more and after one second remove the first of those. That can only be done if each interval has a unique identifier. Once an ID has been used, it’s not available anymore for another interval.

1 Like

timer = setInterval… // timer is not equal to setInterval…
timer1 = setinterval // just this place :slight_smile:

clearInterval(timer1); // At the end of :slight_smile: