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!');
});

2 thoughts on “Creating a Generic jQuery Countdown Timer

  1. Akash Varshney

    thanks !! I was searching for small script.. :)

  2. bappy

    It’s a great article which help me a lot to avoid large code for a simple timer . Thanks a lot bro.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>