10

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?

Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237
  • setInterval let you defined ms as you want by passing a second argument. http://www.w3schools.com/jsref/met_win_setinterval.asp – Mosh Feu Aug 31 '15 at 09:04

4 Answers4

45

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 and event driven system, 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
jfriend00
  • 683,504
  • 96
  • 985
  • 979
4

Yes. Using Date will be much more accurate. setInterval will not be triggered 'exactly' each milliseconds.

var startTime, interval;

function start(){
    startTime = Date.now();
    interval = setInterval(function(){
        updateDisplay(Date.now() - startTime);
    });
}

function stop(){
    clearInterval(interval);
}

function updateDisplay(currentTime){
    // do your stuff
}
Quentin Roy
  • 7,677
  • 2
  • 32
  • 50
0

setInterval could be switchet with

var x = 100; //ms time
var incrementFunction = function(){
     //increment the watch/clock code
 setTimeout(incrementFunction,x);
};
incrementFunction();

this will make a setTimeout function to be endless called, and set again. It seems that setTimeout, has bigger priority than setInterval, which could be delayed.

Radu Toader
  • 1,521
  • 16
  • 23
  • Because the main Javascript execution in a browser is single threaded and can only do one thing at a time, even `setTimeout()` can be delayed. – jfriend00 Aug 31 '15 at 09:16
0

If you need to time something accurately by measuring the date at the start and end of an operation your best best is the Performance API.

const startTime = performance.now();

...    

const duration = performance.now() - startTime;

The time is relative to when the page navigation started, which can also be super useful in and of itself. It works even if someone changes their system clock while the page is loaded!

See also https://developer.mozilla.org/en-US/docs/Web/API/Performance/now

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689