How to measure the milliseconds between mousedown and mouseup?

user166402 picture user166402 · Sep 1, 2009 · Viewed 38.5k times · Source

Is there any way to measure the number of milliseconds between mouse press and release?

Answer

Christian C. Salvadó picture Christian C. Salvadó · Sep 1, 2009

You could create a closure to share two variables, one to store the start time and other for the end time, then in the mouseup event, get the difference:

(function () {
    var element = document.getElementById('element'),
        start, end;

    element.onmousedown = function () {
      start = +new Date(); // get unix-timestamp in milliseconds
    };


    element.onmouseup = function () {
      end = +new Date();

      var diff = end - start; // time difference in milliseconds
    };

})();

Check this working example.