views:

214

answers:

6

How can i time how much time passes between 2 events with javascript? like, to the millisecond?

+2  A: 

Hi,

Well, you can use firebug (firefox plugin) to benchmark your functions. Check this article : benchmark javascript funcions

yoda
You can similarly use the Web Inspector in Safari and Chrome (and other WebKit browsers). The results in these tools will be more reliable and provide more information than manual Date polling.
eyelidlessness
+1  A: 

It's surprisingly difficult to do.

var start = new Date();
// Do things here
var finish = new Date();
var difference = new Date();
difference.setTime(finish.getTime() - start.getTime());
alert( difference.getMilliseconds() );
cpharmston
If you just want the milliseconds, of course, you don't need to create a new date—you just subtract the two times. Also, you can shorten lines 4-5 into: var difference = new Date(finish.getTime() - start.getTime());
Steve Harrison
Oh for the love of ramen. If you have more than 999 milliseconds, this method will not work at all.
Robert L
+1  A: 
var initialTime = (new Date).getTime(), i = 55000;

(function() {
    while ( i-- ) {
        setTimeout( function(){}, 20 );
    }
})()

var finalTime = ( new Date ).getTime(), diff = (new Date);

diff.setTime( finalTime - initialTime );

alert( diff.getMilliseconds() + 'ms' )
meder
A: 

Start with an external variable:

var store = 0;

In your initial listener:

$( "#customID" ).click( function(){
     store = new Date().getTime();
};

In your second listener:

$( "#customID2" ).click( function(){
     handleDifference( new Date().getTime() - store );
};
Christopher W. Allen-Poole
+1  A: 

What about making a reusable timer object?

Usage:

// event 1
document.getElementById('elId').onclick = function () {
  timer.start('myTimer1');
};

// event 2
document.getElementById('otherElement').onclick = function () {
  alert(timer.stop('myTimer1')); // alerts the time difference in ms
};

Implementation:

var timer = (function () {
  var startTimes = {}; // multiple start times will be stored here

  return {
    start: function (id) {
      id = id || 'default'; // set id = 'default' if no valid argument passed
      startTimes[id] = +new Date; // store the current time using the timer id
    },
    stop: function (id) {
      id = id || 'default';
      var diff = (+new Date - startTimes[id]); // get the difference
      delete startTimes[id]; // remove the stored start time
      return diff || undefined; // return the difference in milliseconds
    }
  };
}());
CMS
+1  A: 

When performing arithmetic operations on Date objects, they are implicitly converted to milliseconds (since 1970-01-01 00:00:00 UTC), so all you need to do is subtract a Date created when the operation started from a Date created when the operation ends.

var start = new Date();
doSomeHeavyWork();
var end = new Date();
var millisecondsElapsed = end - start;
gustafc