Introduction to the

define

High Resolution Time Level 3 provides a Time origin and sub-millisecond timing interface (DOMHighResTimeStamp) that is unaffected by the system clock deviation.

【 extend 】

  1. (millisecond) A millisecond (millisecond) specifies a precision higher than millisecond (millisecond).
  2. Date is the approximate timing of milliseconds
background

Ecma-262 defines a Date object that records the number of milliseconds from 00:00:00, January 1, 1970 (UTC) to the current time. The timestamp is DOMTimeStamp

There is a problem
  1. It is not a stable monotonic clock, which will deviate according to the different target systems (such as the start time record between different workers).
  2. Cannot provide subsecond time records
Solution:

Based on the above problems, High Resolution Time provides a performance interface with higher precision (sub-millisecond) and more stability, and its timestamp type is DOMHighResTimeStamp

The Performance interface is exposed in worker and Window globals and provides a series of high-performance computing interfaces. Performance. TimeOrigin records the stable start time

Define the object

Time Origin
Calculation method of starting time:
  1. For the Window object,
    • If there is no pre-document, timeOrigin means that the timer is set up from the browser context
    • If there is a pre-Document and the unload event ends, timeOrigin indicates the point in time before the user confirms the page unload. Okay?
    • The other case is when the window latest Document is loaded
  2. For the WorkerGlobalScope global object, timeOrigin is when the worker was created
  3. In other cases, time Origin is undefined
DOMHighResTimeStamp:

Time metering class of type double, accurate to 5 subtle

The data structure
typedef double DOMHighResTimeStamp;
Copy the code
Performance
The data structure
interface Performance : EventTarget {    
	DOMHighResTimeStamp now();
    readonly attribute DOMHighResTimeStamp timeOrigin;
    [Default] object toJSON();
};
Copy the code
The basic use

Eamples: Compares global times with relative times in the worker

/** worker.js */
onconnect = function(e) {
    const port = e.ports[0];

    port.onmessage = async function(e) {
        // worker executes the task
        const task_start = performance.now();
        const result = await new Promise((resolve) = > {
            setTimeout(() = > {
                resolve(e.data)
           }, 1000)})const task_end = performance.now();
        
        // Send epoch-relative timestamps to other contexts
        const date = Date.now()
        const timeOrigin = performance.timeOrigin

        port.postMessage({ 
            'w_task': 'Some worker task'.'w_task_start': task_start,
            'w_task_end': task_end,
            'w_timeOrigin_add_start_time': task_start + timeOrigin,
            'w_timeOrigin_end_time': task_end + timeOrigin,
            'w_timeOrigin': timeOrigin,
            'w_date': date,
            'index': result, }); }}/** index.js */
const both = document.querySelector('#both');
function reportEventToAnalytics(obj) {
    console.log(obj)
}

// Convert worker timestamp to document time origin timestamp
if(!!!!!window.SharedWorker) {
    const worker = new SharedWorker('worker.js');

    both.onclick = function() {
        const performanceNow = performance.now()
        const dateNow = Date.now()
        const timeOrigin = performance.timeOrigin
        console.log('SendMessage to worker: ', performanceNow, dateNow, timeOrigin)
        worker.port.postMessage({origin: 'both', dateNow, performanceNow,timeOrigin})
   }

    worker.port.onmessage = function (event) {
        console.log('Receive message from worker.js')

        const msg = event.data;
        reportEventToAnalytics(Object.assign({}, msg));

        const timeOrigin = performance.timeOrigin
        // Convert epoch-relative timestamp to Time Origin for docuemnt
        msg.index_start_time = msg.w_timeOrigin_add_start_time - timeOrigin;
        msg.index_end_time = msg.w_timeOrigin_end_time - timeOrigin;

        reportEventToAnalytics(msg);
   }

    worker.port.start()
} else {
    console.log(`Your brower doesn't support SharedWorker API`)}Copy the code

In worker, timeOrigin stays at a fixed value, so timeOrigin can be used to calculate a more accurate time point

(performance.timeorigin +performance.now()) -date.now () has an error of about 8 ms

reference

High Resolution Time Level 3: www.w3.org/TR/hr-time-…