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
2009-09-27 02:52:54
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
2009-09-27 06:55:37
+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
2009-09-27 02:57:44
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
2009-09-27 03:29:34
Oh for the love of ramen. If you have more than 999 milliseconds, this method will not work at all.
Robert L
2009-09-27 04:22:17
+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
2009-09-27 02:59:50
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
2009-09-27 03:02:06
+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
2009-09-27 06:25:32
+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
2010-03-01 09:09:48