While browsing through the jQuery javascript file, I noticed an interesting function used to return the number of milliseconds since January 1st, 1970:

function now() {
    return +new Date;
}

What’s interesting about this function is the use of the + sign before the new operator.  If you omit the + sign, you’ll end up with a regular date object, but including it returns just the number of milliseconds.  It is equivalent to creating a new Date instance and calling getTime() on that instance:

function now() {
    return new Date().getTime();
}

While both function achieve the same result, I really like the simplicity/elegance of the jQuery approach.  And since all elegant code needs a purpose, I decided to wrap it up in a simple javascript timer class:

function Timer() {
    this._start = 0;
    this._end = 0;
    this._isRunning = false;
}

Timer.prototype = {

    start: function() { 
            this._start = this._currentTime(); 
            this._isRunning = true;
        },
            
    stop: function() { 
            this._end = this._currentTime(); 
            this._isRunning = false;
        },
            
    elapsed: function() { 
            if ( this._isRunning )
                return this._currentTime() - this._start;
            else
                return this._end - this._start;
        },

    _currentTime: function() {
            return +new Date; 
        }
};

A simple way to use it would be to time a long running operation:

var timer = new Timer;
timer.start();

// Insert long running operation here...
timer.stop();

alert('Operation took ' + timer.elapsed() + ' ms.');

While our timer is relatively simple, it does allow the option to get the elapsed time while the Timer is still running:

var timer = new Timer;

timer.start();

// Insert an operation here...

var elapsedTimeA = timer.elapsed();

// Insert a second operation here....

timer.stop();

alert('First Operation took ' + elapsedTimeA + ' ms. Total operation took ' + timer.elapsed() + ' ms.');

And that’s all there is to using our simple Timer object!

Some possible enhancements that might be useful:

  • Adding a constructor parameter to specify auto-starting the Timer,
  • Implementing split times ( which would turn it more into a stopwatch class )
  • Providing different measurements for the return value ( Minutes, Seconds, Hours, etc. )

I’ll be revisiting the timer in future posts, so we may be seeing those features soon!

- Colin