High Resolution Time Stamp for Events Sample

Available in Chrome 49+ | View on GitHub | Browse Samples

Background

The timeStamp property of the Event interface indicates the time at which a given event took place.

Previously, this timeStamp value was represented as a DOMTimeStamp, which was a whole number of milliseconds since the system epoch.

Starting with Chrome 49, timeStamp is a DOMHighResTimeStamp value. This value is still a number of milliseconds, but with microsecond resolution, meaning the value will include a decimal component. Additionally, instead of the value being relative to the epoch, the value is relative to the PerformanceTiming.navigationStart, i.e. the time at which the user navigated to the page.

To convert the a DOMHighResTimeStamp value to an absolute number of milliseconds since the epoch (e.g., to get a value to pass to the Date() constructor), use event.timeStamp + performance.timing.navigationStart.

Live Output

The following sample provides a rough approximation of mouse pointer velocity, with a higher precision on browsers that support DOMHighResTimeStamp. (In this contrived example, the difference in resolution between DOMHighResTimeStamp and DOMTimeStamp won't make a significantly affect the calculations, since the change in pixel positions are relatively coarse.)

Your mouse velocity, in pixels per second:


JavaScript Snippet

var previousX;
var previousY;
var previousT;

window.addEventListener('mousemove', function(event) {
  // Don't update velocity until we have an initial value for X, Y, and T.
  if (!(previousX === undefined ||
        previousY === undefined ||
        previousT === undefined)) {
    var Δx = event.screenX - previousX;
    var Δy = event.screenY - previousY;
    var Δd = Math.sqrt(Math.pow(Δx, 2) + Math.pow(Δy, 2));

    // event.timeStamp will always represent a value in milliseconds.
    // In supported browsers, the value will have a microsecond resolution, and
    // therefore might include a fractional number of milliseconds.
    // Older browsers only support a millisecond resolution, and the value will
    // always be a whole number.
    var Δt = event.timeStamp - previousT;

    // Multiply by 1000 to go from milliseconds to seconds.
    var velocityInPixelsPerSecond = Δd / Δt * 1000;

    ChromeSamples.setStatus(velocityInPixelsPerSecond);
  }

  previousX = event.screenX;
  previousY = event.screenY;
  previousT = event.timeStamp;
});