26
Aug
2009
[Javascript] Time, timers and time differences
This should be easy, and perhaps I’m making it harder then it should be… I’m used to using the DateTime object, which confuses me when I have to switch back to javascript.
Anyhoot… here is how I have created a pseudo-timer that will spit out the time difference in seconds from when the timer is started to when it is stopped.
Obviously this is simple, and can only time one thing at any given time… but you get the idea.
var startTime;
function startTimer()
{
// Set the global start time to "now"
startTime = new Date();
}
function findTimeDiff(message)
{
// Uses the global startTime.
// valueOf() spits out in milliseconds, so /1000 to get seconds.
var diffInSeconds = ((new Date()).valueOf() - startTime.valueOf())/1000;
alert(message + " [" + diffInSeconds + " seconds]");
}
...
startTimer();
LengthyFunction();
findTimeDiff("Time to run LengthyFunction");
startTimer();
LengthyFunction2();
findTimeDiff("Time to run LengthyFunction2");
Tags: javascript
This entry was posted
on Wednesday, August 26th, 2009 at 10:16 am and is filed under javascript.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

I just happen to be working with JS right now too! Had the inspiration to wrap the functions into an object so there can be multiple instances
The things that bring programmers joy.
function TimeDiff()
{
var startTime;
this.Start = function() {
// Set the global start time to “now”
startTime = new Date();
};
this.Stop = function(message) {
// Uses the global startTime.
// valueOf() spits out in milliseconds, so /1000 to get seconds.
var diffInSeconds = ((new Date()).valueOf() – startTime.valueOf())/1000;
alert(message + ” [" + diffInSeconds + " seconds]“);
};
}
Thank you Chris