Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, how to create an accurate timer with milliseconds?

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?

like image 233
Hanfei Sun Avatar asked Aug 31 '15 08:08

Hanfei Sun


People also ask

How do you write every 5 seconds in JavaScript?

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.

Does JavaScript have a timer function?

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.

What JavaScript method can be used to call another method after a number of milliseconds has passed?

The native JavaScript setTimeout function calls a function or executes a code snippet after a specified delay (in milliseconds).


1 Answers

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
like image 186
jfriend00 Avatar answered Sep 28 '22 06:09

jfriend00