performance.now example
👉 Overview
👀 What ?
Performance.now is a method provided by the High Resolution Time API, a part of the JavaScript language used in browsers. It provides a way to get the current time in milliseconds with a significantly higher precision than other methods, such as Date.now().
🧐 Why ?
Performance.now is important because it allows developers to measure the time taken by certain parts of their code more accurately. This is crucial for performance testing and optimization, especially in complex web applications where small differences in execution time can have a large impact on user experience. It can also be useful in other scenarios where precise timing is required, such as animation or game development.
⛏️ How ?
To use performance.now, simply call the method without any arguments. It will return the current time in milliseconds, measured from the time the page started to load (also known as 'time origin'). Here's an example of how to use it to measure the time taken by a function: \n\n
javascript\nvar start = performance.now();\n// Code to be timed goes here\nvar end = performance.now();\nconsole.log('Execution time: ' + (end - start) + ' ms');\n
⏳ When ?
The performance.now method was introduced as part of the High Resolution Time API, which was published as a W3C Recommendation in December 2012. It has been supported in most major browsers since around that time.
⚙️ Technical Explanations
Performance.now works by giving access to a high-precision monotonic clock, which is not subject to system clock skew or adjustments. The time origin it uses is defined by the PerformanceTiming.navigationStart property, which represents the moment the user agent finished prompting to unload the previous document. If no previous document exists, like in the case of a newly opened tab or window, the navigationStart will be equivalent to the time origin. The time is returned as a DOMHighResTimeStamp, which is a double-precision floating-point value accurate to the microsecond, but is usually rounded to the nearest millisecond in practice.