views:

533

answers:

3

Looks like you can't call setInterval() from the onMouseDown event handler. I tried, didn't work.

By John Resig's explanation, this makes sense: http://ejohn.org/blog/how-javascript-timers-work/

So is there any way to measure the difference between the mouse button gets depressed and when it gets released?

A: 

You can use two global variables to record the time of mousedown and mouseup, and have a substract

liujinmarshall
+1  A: 

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.

CMS
how to write this code so fast??
Shoban
@Shoban: http://www.vim.org/
CMS
.. although I think that being a fast typist is not a real down-voting reason, since I'm providing a valid answer... :)
CMS
A: 

When onmousedown is fired you can hang an onmouseup event on window. This will allow to avoid unnecessary closures.

el.onmousedown = function () {
  var time = new Date(); //time in milliseconds
  window.onmouseup=function(){
    var diff=new Date()-time;
    window.onmouseup=null;
  }
};

check result here: http://jsbin.com/uneqo

Eldar Djafarov