Sometimes, we want to get a high-resolution timestamp with JavaScript.
In this article, we’ll look at how to get a high-resolution timestamp with JavaScript.
Get a High-Resolution Timestamp with JavaScript
To get a high-resolution timestamp with JavaScript, we can use the window.performance.now or window.performance.webkitNow methods.
For instance, we write:
let getTimestamp;
if (window.performance.now) {
getTimestamp = () => {
return window.performance.now();
};
} else {
if (window.performance.webkitNow) {
getTimestamp = () => {
return window.performance.webkitNow();
};
} else {
getTimestamp = () => {
return new Date().getTime();
};
}
}
console.log(getTimestamp());
We can use window.performance.now if it’s available with:
if (window.performance.now) {
getTimestamp = () => {
return window.performance.now();
};
}
We set getTimestamp to a function that returns the timestamp from window.performance.now .
Otherwise, we set getTimestamp to a function that returns the timestamp from window.performance.webkitNow .
And if that’s not available, we set getTimestamp to a function that returns the timestamp from the getTime method.
Conclusion
To get a high-resolution timestamp with JavaScript, we can use the window.performance.now or window.performance.webkitNow methods.