Does JavaScript provide a high resolution timer?

Almost all modern browsers provide a high resolution timer. It’s the “High Resolution Time” W3C standard: http://www.w3.org/TR/hr-time/#sec-DOMHighResTimeStamp.

It allows you to get a sub-millisecond accurate timestamp by calling window.performance.now(). This returns a time stamp in ms, but it is a float so you still get sub-millisecond resolution.

Very old browsers may implement a “prefixed” version of this standard, e.g. WebKit based browsers used to implement window.performance.webkitNow()

Here is some code you can use to get the the accurate timestamp when available and fallback to standard precision otherwise:

if (window.performance.now) {
    console.log("Using high performance timer");
    getTimestamp = function() { return window.performance.now(); };
} else {
    if (window.performance.webkitNow) {
        console.log("Using webkit high performance timer");
        getTimestamp = function() { return window.performance.webkitNow(); };
    } else {
        console.log("Using low performance timer");
        getTimestamp = function() { return new Date().getTime(); };
    }
}

getTimestamp();

Note that this getTimestamp() function does not return a value that represents the current date/time. The returned value can only be used to measure time-periods, by subtracting two different timestamps.
E.g.

var t1 = getTimestamp();
//... some other code
var t2 = getTimestamp();
console.log("Time delta: " + (t2 - t1));

Leave a Comment