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:
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).now()
is monotonically increasing. This is important asDate.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()
.
Microsecond or at least sub-millisecond timing in a web-worker?
There's a performance
property on WorkerGlobalScope
. It's not super-widely supported, but then again neither are web workers.
Specifically, .now()
is (apparently) available to web workers, if that's all you need.
Date.now() returns a value in microseconds and not in milliseconds
The current epoch time (AKA unix timestamp), 1554637856
is the number of seconds since 01-01-1970, not milliseconds.
Date.now()
returns the epoch time in milliseconds, so you'd want seconds:
if (endTime <= now / 1000) {
...
set time interval for javascript function in microseconds
4 ms is the minimum timeout in standard HTML5 according to the spec
See this reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Minimum_delay_and_timeout_nesting
You may think you can assign any amount of duration in millisecond which is as small as you want in JavaScript, however, it is limited by the HTML5 spec that the minimum delay (DOM_MIN_TIMEOUT_VALUE) implemented in modern browsers are set to 4 ms. Even more, Firefox implements it 5 ms.
jQuery is implemented on top of JavaScript and therefore complies this rule. So, it's not possible to achieve "micro or nano seconds of delay" in JavaScript at all.
Get ISOString in microseconds from unix timestamp
So is there a way to get the output in microsecond format ?
Not using built–in methods. You can add the microsecond part yourself though. It's best to use string methods to get the digits to preserve leading zeros:
// Time value in microsecondslet tv = 1576681153064071;// Get millisecond partlet msec = tv/1000;// Get microsecond part - keep leading zeroslet μsec = String(tv).slice(-3);// Get ISO 8601 timestamplet isoDate = new Date(msec).toISOString();// Add in microsecondslet isoDatePlus = isoDate.replace('Z', μsec + 'Z');
console.log(isoDatePlus);
milliseconds to time in javascript
Lots of unnecessary flooring in other answers. If the string is in milliseconds, convert to h:m:s as follows:
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
If you want it formatted as hh:mm:ss.sss then use:
function msToTime(s) {
// Pad to 2 or 3 digits, default is 2 function pad(n, z) { z = z || 2; return ('00' + n).slice(-z); }
var ms = s % 1000; s = (s - ms) / 1000; var secs = s % 60; s = (s - secs) / 60; var mins = s % 60; var hrs = (s - mins) / 60;
return pad(hrs) + ':' + pad(mins) + ':' + pad(secs) + '.' + pad(ms, 3);}
console.log(msToTime(55018))
Is there any way to get current time in nanoseconds using JavaScript?
Achieve microsecond accuracy in most browsers using:
window.performance.now()
See also:
- https://developer.mozilla.org/en-US/docs/Web/API/Performance.now()
- http://www.w3.org/TR/hr-time/
- https://caniuse.com/high-resolution-time
Related Topics
Jquery - Create Hidden Form Element on the Fly
Get Query String Parameters Url Values with Jquery/JavaScript (Querystring)
Put JavaScript in One .Js File or Break It Out into Multiple .Js Files
Jqgrid Gridunload/ Griddestroy
JavaScript While Loop Return Value
Disable Hover Effects on Mobile Browsers
React.Js Replace Img Src Onerror
Cross Domain Post Request Is Not Sending Cookie Ajax Jquery
Checking for Duplicate Strings in JavaScript Array
How to Catch Exceptions Thrown in a JavaScript Async Callback
Get Index of Clicked Element Using Pure JavaScript
Jquery Clone Form Fields and Increment Id
Replace All Occurrences in a String
Dynamic Extension Context Menu That Depends on Selected Text
Differencebetween Unary Plus/Number(X) and Parsefloat(X)
JavaScript Equivalent of Jquery's Extend Method
Disabling the Long-Running-Script Message in Internet Explorer