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;
      if (seconds > 0)
         setTimeout(timer,tick * 1000);
         cb && cb();
    setTimeout(timer,tick * 1000);
    return this;

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:


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() {