Creating a Generic jQuery Countdown Timer

I needed to create many HTML countdown timers for a little pet project of mine. So, I wrote a jQuery selector function to create countdown timers on demand. These timers are really simple, they countdown for a number of seconds to zero.

Add this to your scripts:

(function($) {
  $.fn.createCountdownTimer = function(selector,time,tick,cb) {
    var seconds = time;
    var el = this;
    tick = tick || 1;
    var timer = function() {
      seconds -= tick;
      el.find(selector).text(String(seconds));
      if (seconds > 0)
         setTimeout(timer,tick * 1000);
      else
         cb && cb();
    };
    setTimeout(timer,tick * 1000);
    return this;
 };
})(jQuery);

Parameters tick and cb are optional. tick defaults to 1 as you usually tick down 1 second at a time.

Suppose you have a HTML countdown timer such as:

<div id="my_timer">Starting in <span class="timer">10</span> seconds...</div>

then, all you need to do to start a countdown from 10 to 0 is:

$("#my_timer").createCountdownTimer(".timer",10);

You can also supply a callback as a fourth parameter that will be called when the timer is done counting to zero. For example:

$("#my_timer").createCountdownTimer(".timer",10,1,function() {
   alert('Done!');
});