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!
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;
});
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.