Categories
JavaScript Answers

How to Get the Current Time in Nanoseconds Using JavaScript?

Spread the love

To get the current time in nanoseconds using JavaScript, we can use the window.performance.now method and window.performance.timing.navigationStart properties.

For instance, we can write:

const ms = window.performance.timing.navigationStart + window.performance.now()  
const ns = ms / 0.001  
console.log(ns)

to get the current timestamp in nanoseconds.

window.performance.timing.navigationStart returns the timestamp in milliseconds when we run the code.

And window.performance.now returns the number of nanoseconds since the code has run.

Then to convert the timestamp in milliseconds to nanoseconds, we divide ms by 0.001.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.