Sunday, April 01, 2007

Javascript Timer

It is beautifully simple, yet jQuery has completely changed my approach to UI design. I've been using it for a couple of weeks now and have almost finished moving all my code over to the world jQuery.

In my short time working with jQuery, I wanted to measure just how well jQuery performed in contrast with my old JavaScript library. So I devised a very simple JavaScript timer object. The aim is for it to work like a stopwatch. Start the timer, then stop it and show how much time has passed (in milliseconds) since it was started.

The code:
Enough chitty-chat, show me the good stuff.

var timer = {
time: 0,
now: function(){ return (new Date()).getTime(); },
start: function(){ this.time = this.now(); },
since: function(){ return this.now()-this.time; }
}


Usage:
How to use it...
timer.start(); // start counting my friend...
/*
do some amazing stuff with jQuery or any other JavaScript library
*/
alert('I did all that in ' + timer.since() + 'ms');


Other things:
Setting up checkpoints - The good thing is that the 'timer' will 'continue running' until you restart it (by calling the timer.start() method). That way you can easily set up checkpoints within your code with having to define several variables, etc...
timer.start(); // start counting my friend...
/* do stuff */
alert('Checkpoint 1: ' + timer.since() + 'ms since start');
/* do more stuff */
alert('Checkpoint 2: ' + timer.since() + 'ms since start');
/* do yet more stuff */
alert('Checkpoint 3: ' + timer.since() + 'ms since start');

timer.start(); // let's reset

/* yep, you guessed it, do yet more and more stuff */
alert('Checkpoint 1b: ' + timer.since() + 'ms since last re-start');

Happy jQuerying everybody!

2 comments:

David said...

A very compact and usable development tool. Rock on!

I've used it a few times in my work today already, and it is an excellent middle path between rolling my own and using some monstrosity of a framework. Thanks!

Raymond said...

Great little bit of code. So simple in its methods and in its implementation.

Used it for this: http://metronome.pianowithraymond.com