Tiny Cute JavaScript Stopwatch


Before you start reading: this page is NOT about a stopwatch for people to start and stop.

This page is about creating a feather-light stopwatch object inside your JS programs, pass it around and using it to measure the elapsed time.

It may tell your page when it’s time to quit waiting for that file to download, get rid of the sandclock on the screen and get on with life.

The tiny cute code:

It’s all in a function: it accepts a duration and returns an object that you can interrogate to know if the duration time has passed.

var stopwatch = function(duration) {
  var _running = true;
  (function() { setTimeout(function() { _running=false; }, duration); } )();
    running: function() { return _running; }

There is a timer (an anonymous self-executing function) that starts ticking at construction time. After the given duration, a private flag will be set to false. Time is over.

How to use it:

You create a stopwatch like this:

var myStopwatch = stopwatch(6000)

and pass it to the methods you invoke, or keep it for yourself. At any moment you may ask:

if (myStopwatch.running()) { . . . . . . . }

and check whether those 6 seconds have passed or not yet.

Other variations on this theme could be:

  • a stopwatch that (upon interrogation) fires an exception and gets interrogated by a try/catch block (but I prefer this simpler one)
  • a stopwatch that fires a global event (upon interrogation or by itself at the end of the elapsed time) and potentially gets the attention of the whole window

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s