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

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=""> <s> <strike> <strong>