0

I am just trying to create a simple counter using setInterval. However, after 5 seconds, the interval slows down to about 1000ms. I'm sure I am just overlooking something silly, but for the life of me I cant see it.

var btn = document.getElementById("btn");
var num = document.getElementById('num');
btn.addEventListener("click", startCounter);

var interval;

function startCounter(){
  interval = setInterval(count, 100);
}

var idx = 0;

function count(){
  idx++;
  console.log(idx);
  num.textContent = idx;
  if(idx > 100) {
    clearInterval(interval);
    idx = 0;
  }
}
<button id="btn">Click</button>
<div id="num" style="">0</div>
Mike
  • 2,299
  • 13
  • 49
  • 71
  • 2
    It's working as expected for me in Chrome. – David Jan 10 '23 at 19:50
  • you also leak your timer handle – Daniel A. White Jan 10 '23 at 19:50
  • It's working fine as expected, I don't see any lag or issues in this code. – Sachin Dane Jan 10 '23 at 19:52
  • 2
    I guess that you change your active tab. The minimal interval time in an inactive tab is one second https://stackoverflow.com/questions/5927284/how-can-i-make-setinterval-also-work-when-a-tab-is-inactive-in-chrome – Konrad Jan 10 '23 at 19:53
  • Have you tried restarting your computer? :D – henrik Jan 10 '23 at 19:54
  • Oh weird. It works in FF and Chrome, but not in Edge. – Mike Jan 10 '23 at 19:55
  • Even after installing the latest Edge update, it doesn't work. Very bizarre. I guess I'll switch to another browser. – Mike Jan 10 '23 at 19:59
  • There are a bunch of reasons why an interval might be longer than expected. They are outlined [here](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified). `setInterval` follows the same rules as `setTimeout`. – Ben Aston Jan 11 '23 at 10:50

0 Answers0