I’ve recently been deep into an HTML project with some tricky Javascript involved. At one point it turned out I had a real need to be able to discretely time parts of the system. You know, I found myself in that “what is eating all my time here” place.

The developer tools (thanks Firebug for leading this charge years ago) have gotten incredibly sophisticated. There are all sorts of ways to tell where time is being spent as well as the details inside of each element. But there are times when you want to be in control of what is being timed.

Thanks to moving around in many languages over the last decade I have these kinds of tools already built. I’ve built them in Perl, Java, Objective-C, J2ME, JScript… but not in Javascript. It was time for a port.

Months back I found myself in this spot for an iOS project and had to build a simple timer class (stopwatch) that would be as simple to use as possible, but also extensible and with as low an overhead as possible. That created MMStopwatch for Objective-C. And it worked so well and so easily I thought I’d try as direct a port as possible to Javascript.

 

The Stopwatch

Okay, on to the details. The port to Javascript is complete but with a few differences. It is terribly efficient and has almost no overhead. And using it is as simple as the Objective-C version.

How to use:

The “name” of the stopwatch is it’s key. So you can create as many as you like with the same interface. Calling “describe” with the name will print out the current elapsed time (if still running) or total time (if stopped). It simply cannot be easier.

There is one library to pull and include: MMStopWatch.js

Then your output will spit out:

As always: use this in any way you like without any need for attribution in any way.

JSFiddle

I also put together a quick JSFiddle with this. Maybe that will help you understand usage and how quick you will be timing your code:

http://jsfiddle.net/bladnman/wR27b/

 

Edit (10/10/2012): I updated the way I’m displaying MS now.