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!
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