How can i time how much time passes between 2 events with javascript? like, to the millisecond?
-
3It's worth noting that the accuracy of Javascript timing can be pretty questionable, both in terms of async code (setTimeout, setInterval) and in terms of polling duration (as with the answers given here).eyelidlessness– eyelidlessness2009年09月27日 06:52:52 +00:00Commented Sep 27, 2009 at 6:52
6 Answers 6
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;
Comments
Easiest way to do this.
console.time("timer name")
console.timeEnd("timer name")
This will output the time in milliseconds to the console.
Comments
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() );
2 Comments
Well, you can use firebug (firefox plugin) to benchmark your functions. Check this article : benchmark javascript funcions
1 Comment
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
}
};
}());
1 Comment
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' )