Home Web Front-end JS Tutorial Discovering the High Resolution Time API

Discovering the High Resolution Time API

Feb 24, 2025 am 09:33 AM

Discovering the High Resolution Time API

Core points

  • High Resolution Time API is a JavaScript interface that provides current time with submillisecond resolution, not affected by system clock deviation or adjustment, and provides more reliable and accurate performance measurement options than traditional Date.now() methods. .
  • The high-resolution time API is not widely supported by all browsers, mainly supporting Internet Explorer 10, Firefox 15 (unprefixed), and Chrome 20 (with the "webkit" prefix). It is recommended to use functions to test browser support and prefix usage.
  • Developers can easily integrate high-resolution time APIs into their code by replacing Date.now() with performance.now(), thus improving measurement accuracy without major changes to the code structure.

In today's world, performance is crucial. Developers need to be able to accurately measure the performance of their software. For those engaged in web development, W3C provides a brand new API to reliably time count, which is the high resolution time API. This article will explore the high-resolution time API and show how to use it. To measure the performance of functions, web developers used to use the JavaScript method. Usually, the timing code looks like this:

Date.now()

Method retrieves the current time stamp based on system time. Unfortunately, its accuracy varies between different user agents and is therefore not very reliable. To solve this problem, W3C standardizes the high-resolution time API. The API is described as "
var startTime = Date.now();

// 一个耗时的函数
foo();
var test1 = Date.now();

// 另一个耗时的函数
bar();
var test2 = Date.now();

// 打印结果
console.debug("Test1 time: " + (test1 - startTime));
console.debug("Test2 time: " + (test2 - test1));
Copy after login
Copy after login
A JavaScript interface that provides the current time of submillisecond resolution and is not affected by system clock deviation or adjustments

". On October 23, 2012, the specification became the W3C recommendation recommendation—the last step before it became the recommendation. On December 17, it became the W3C recommendation (updated on December 17). Date.now() How to work with high resolution time API

I must admit that this is the easiest API I have ever read because it contains only one method. This API extends the Performance interface, which is also used by the Navigation Timing API. If you've never heard of it, check out the Navigation Timing API: How to analyze page loading effectively. The only way to be exposed is now(), which returns a DOMHighResTimeStamp indicating the current time in milliseconds. The timestamp is very accurate, with an accuracy of one thousandth of a millisecond. Note that although Date.now() returns the number of milliseconds elapsed since 00:00:00 UTC on January 1, 1970, performance.now() returns the number of milliseconds invoked from performance.timing.navigationStart() (the document navigation starts) to performance.now(), The fractional part is microseconds. Another important difference between Date.now() and performance.now() is that the latter is monotonically increasing, so the difference between the two calls will never be negative. Maybe you're wondering how the high resolution time API will change your code. The good news is that it won't change anything. You can improve the accuracy of your measurements by simply replacing Date.now() with performance.now(). With this in mind, the previous code will be rewritten as follows:

var startTime = Date.now();

// 一个耗时的函数
foo();
var test1 = Date.now();

// 另一个耗时的函数
bar();
var test2 = Date.now();

// 打印结果
console.debug("Test1 time: " + (test1 - startTime));
console.debug("Test2 time: " + (test2 - test1));
Copy after login
Copy after login

Compatibility

Currently, only a few browsers support high-resolution time APIs. The only desktop browsers that support this API are Internet Explorer 10, Firefox 15 (unprefixed), and Chrome 20 (with "webkit" prefix, performance.webkitNow()). Chrome seems to be using the unprefixed version starting with version 24. At the time of writing, no mobile browser supports this API. Since the support range is not wide, a function is first needed to test the browser support situation and whether it is prefixed. The following function will return an empty string when the browser uses the unprefixed version of the API. If a prefixed version is used, the prefix is ​​returned. If the API is not supported, return null.

var startTime = performance.now();

// 一个耗时的函数
foo();
var test1 = performance.now();

// 另一个耗时的函数
bar();
var test2 = performance.now();

// 打印更精确的结果
console.debug("Test1 time: " + (test1 - startTime));
console.debug("Test2 time: " + (test2 - test1));
Copy after login

For browsers that do not support this API, you can use a shim. Shim's author Tony Gentilcore is one of the contributors to the API. In his post titled "A better timer for JavaScript", Gentilcore wrote code that first searches for native support and then uses the Date.getTime() method as a fallback. The code looks like this:

function getPrefix() {
  var prefix = null;
  if (window.performance !== undefined) {
    if (window.performance.now !== undefined)
      prefix = "";
    else {
      var browserPrefixes = ["webkit","moz","ms","o"];
      // 测试所有厂商前缀
      for(var i = 0; i < browserPrefixes.length; i++) {
        if (window.performance[browserPrefixes[i] + "Now"] != undefined) {
          prefix = browserPrefixes[i];
          break;
        }
      }
    }
  }
  return prefix;
}
Copy after login

Integrate all content

This section will guide you through a simple demo page. The demo will first test the browser support, and then use a function called doBenchmark which relies on two virtual functions to benchmark using the performance.now() method. Note that I introduced an API-independent getTime() function. Its sole purpose is to avoid unnecessary duplication and make the code more concise. The source code for the demonstration is as follows: (The lengthy sample code is omitted here because it does not match the question requirements and is too long)

Conclusion

In this article, I've covered what the high resolution time API is and how to use it. As I mentioned, it hasn't been widely supported yet, so to accurately test your web application you'll have to wait for a while. However, as you can see, the API is very simple because it contains only one method. Therefore, once browser support is improved, migration to high resolution time will be quick and easy.

(The FAQs part is omitted here because it does not match the question requirements and is too long)

The above is the detailed content of Discovering the High Resolution Time API. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1654
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

See all articles