I saw a Javascript milliseconds timer demo HERE
However, I found it very inaccurate because it uses setInterval
to increase one ms per time.
Does anyone have ideas about how to implement an accurate milliseconds timer in JS easily? Does it has to be done using Date
object?
To call a JavaScript function every 5 seconds continuously, we call setInterval with the function that we want to run and the interval between runs. const interval = setInterval(() => { // ... }, 5000); clearInterval(interval); to call setInterval with the callback we want to run and 5000 millisecond period.
There are two timer functions in JavaScript: setTimeout() and setInterval() . The following section will show you how to create timers to delay code execution as well as how to perform one or more actions repeatedly using these functions in JavaScript.
The native JavaScript setTimeout function calls a function or executes a code snippet after a specified delay (in milliseconds).
An accurate timer uses setTimeout()
or setInterval()
to regularly update a display, but NEVER to count the actual time. Because of Javascript's single threaded nature, a timer event may not occur exactly at the right time interval, but a call to Date.now()
will always give you the exact current system time.
So, instead, you always use something like Date.now()
to get the current time and compare it to some previous time to calculate the actual elapsed time. This will be as accurate as the system clock on the computer is.
For example, here's a working timer display:
var startTime = Date.now();
var interval = setInterval(function() {
var elapsedTime = Date.now() - startTime;
document.getElementById("timer").innerHTML = (elapsedTime / 1000).toFixed(3);
}, 100);
<span id="timer"></span> s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With