Search code examples
javascriptperformancecountdownlag

Sync JavaScript timer with browser performance


Let's say I'm running a laggy app in the background of my computer.

This lag also affects the browser's performance (in this case Firefox).

And now, I build a JavaScript timer with this code:

let seconds = 10;
let countdown = setInterval(() => {
  if (seconds <= 0) return clearInterval(countdown);
  document.querySelector("#timer").textContent = seconds;
  seconds--;
}, 1000);

This timer would work fine if my performance wasn't so bad.

Delayed timer example

Look closely at the number countdown, and you can see how the delay always changes from 1 second - 3 seconds.

How can I make this countdown sync with the performance, so it always decrements 1 second instead of delaying?


Solution

  • Try using a recursive setTimeout instead, it should be more consistent than setInterval.

    let seconds = 10;
    let countdown = setTimeout(function countdownCallback() {
      if (seconds <= 0) return;
      document.querySelector("#timer").textContent = seconds;
      seconds--;
      setTimeout(countdownCallback,1000);
    }, 1000);
    

    If that doesn't work then there's nothing else that can be done.