1

Sometimes, I found that setInterval will be inaccurate and unreliable.

For example,

let time = document.querySelector("div");
setInterval(function () {
  console.log(window.getComputedStyle(time).getPropertyValue("opacity"));
  time.textContent = parseFloat(time.textContent) + 1;
}, 1);
<div>0</div>

The timer is much slower than 1 ms which means the setInterval doesn't work properly.

Why does this happens?

What is a much better and reliable alternative option for setInterval?

Thanks for any responds!

AKX
  • 152,115
  • 15
  • 115
  • 172
James
  • 2,732
  • 2
  • 5
  • 28
  • 1
    You could use `requestAnimationFrame()` instead. Depends on what you want to achieve, though. – AKX Jan 02 '22 at 20:14
  • 1
    The minimum interval is about 4ms. You can't get below that – charlietfl Jan 02 '22 at 20:14
  • The time you set (or that is given as value in the docs) for timers is the minimum amount the timer needs to wait until it calls the callback. But the time could be much longer. If you want to have a counter that reflects time you need store the start time and calculate the elapsed one yourself. – t.niese Jan 02 '22 at 20:19
  • 1
    To answer your 'why' question: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified (the link is for `setTimeout`, but the same reasons apply). – yaken Jan 02 '22 at 21:00
  • 2
    Does this answer your question? [How to create an accurate timer in javascript?](https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript) – Neil VanLandingham Jan 02 '22 at 21:56
  • If you get your answer, please accept the answer.! – Mohammad Hossein Dolatabadi Jan 06 '22 at 08:29

1 Answers1

1

setTimeout and setInterval in javascript only promise that they won't be run before the specific time. they try to execute your function as soon as possible but they sometimes can't do that. They are not timers. They are some functions that call a callback after a time which is the minimum amount of waiting before calling the callback function. Unfortunately there is not an accurate timer in javascript. you can implement it yourself.
Edit: you may ask how:
read the following thread: https://stackoverflow.com/a/29972322/12337783