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

Building on Jeffery's answer, to get an absolute time-stamp (as the OP wanted) the code would be:

var TS = window.performance.timing.navigationStart + window.performance.now();

result is in millisecond units but is a floating-point value reportedly "accurate to one thousandth of a millisecond".


In Server side environments like Node.js you can use the following function to get time in nanosecond

function getNanoSecTime() {
  var hrTime = process.hrtime();
  return hrTime[0] * 1000000000 + hrTime[1];
}

Also get micro seconds in a similar way as well:

function getMicSecTime() {
  var hrTime = process.hrtime();
  return hrTime[0] * 1000000 + parseInt(hrTime[1] / 1000);
}