2

Is there a way to measure the latency between when I press my mouse button and when a defined onmousedown function fires?

Or, are there current statistics available about this latency?

I assume these two events are not simultaneous, and vary by browser.

My only approach so far has been to create multiple onmousedown events and measure the time difference between them using Date. I found up to a 6ms difference between them.

I am working on audio applications which are time-sensitive (to milliseconds).

Any help is great, thanks!

suncannon
  • 194
  • 1
  • 9
  • I am interested specifically in desktop browsers; I'm aware of the 300ms delay in mobile events, but that's not what I'm trying to measure. – suncannon Feb 23 '15 at 18:13
  • Using JavaScript for timing-sensitive functions may not be your best choice. I'd recommend exploring other tools with better-defined specifications for that kind of application. – Palpatim Feb 23 '15 at 18:17
  • _"Using JavaScript for timing-sensitive functions may not be your best choice."_ - Also keep in mind that **JavaScript is single-threaded**. – John Weisz Feb 23 '15 at 18:32
  • Thanks, yes I'm aware that JS is generally not a good choice for time-sensitive applications. However, when working with the Web Audio API, getting timing as accurate as possible (given the circumstances) is important. – suncannon Feb 23 '15 at 18:56
  • @JánosWeisz: Single-threading shouldn't mean much for latency. You can still keep your app reactive using certain optimisations (doing really heavy stuff in webworkers for example) – Bergi Feb 23 '15 at 19:00

1 Answers1

3

You are likely looking for the difference between Event.timeStamp and the current timestamp, Date.now(). They both return the elapsed time since the epoch in milliseconds:

JavaScript

document.getElementById("mydiv").addEventListener('click', function (e) {
    // in milliseconds
    var latency = Date.now() - e.timeStamp;
});

Working example on JSFiddle.

By subtracting the former from the latter - as you can see in the included snippet - you can measure latency.

Unfortunately, the event timeStamp is not the actual hardware moment the mouse was clicked, but rather when the browser received the click event from your OS. This, however, always happens before the event handler is called, and should have negligible latency.

Regarding the linked fiddle, the time differences for me are below 1ms most of the time; I've occasionally managed to achieve values above 10ms with merciless button smashing and page reloading, but it's not common. Of course, if you do more computationally intensive tasks in your event handlers, the difference can easily climb, in which case latency compensation can quickly become an essential part.

John Weisz
  • 30,137
  • 13
  • 89
  • 132