Microsecond timing in JavaScript

As alluded to in Mark Rejhon’s answer, there is an API available in modern browsers that exposes sub-millisecond resolution timing data to script: the W3C High Resolution Timer, aka window.performance.now().

now() is better than the traditional Date.getTime() in two important ways:

  1. now() is a double with submillisecond resolution that represents the number of milliseconds since the start of the page’s navigation. It returns the number of microseconds in the fractional (e.g. a value of 1000.123 is 1 second and 123 microseconds).

  2. now() is monotonically increasing. This is important as Date.getTime() can possibly jump forward or even backward on subsequent calls. Notably, if the OS’s system time is updated (e.g. atomic clock synchronization), Date.getTime() is also updated. now() is guaranteed to always be monotonically increasing, so it is not affected by the OS’s system time — it will always be wall-clock time (assuming your wall clock is not atomic…).

now() can be used in almost every place that new Date.getTime(), + new Date and Date.now() are. The exception is that Date and now() times don’t mix, as Date is based on unix-epoch (the number of milliseconds since 1970), while now() is the number of milliseconds since your page navigation started (so it will be much smaller than Date).

now() is supported in Chrome stable, Firefox 15+, and IE10. There are also several polyfills available.

Note: When using Web Workers, the window variable isn’t available, but you can still use performance.now().

Leave a Comment