How to create a countdown timer with jQuery?

Only Bolivian Here picture Only Bolivian Here · Aug 29, 2011 · Viewed 24.6k times · Source

I'll have more than one of these small boxes on my site, and each will start counting down at different times.

How can I decrease the numerical value of the timer per second, giving the simulation of a countdown timer?

enter image description here

<p class="countdown">15</p>

Using this javascript it correctly countsdown, but every single auctionbox is affected. How would you suggest I isolate the timer to act on only one item?

<script>
var sec = 15
var timer = setInterval(function() {
   $('.auctiondiv .countdown').text(sec--);
   if (sec == -1) {
      $('.auctiondiv .countdown').fadeOut('slow');
      clearInterval(timer);
   }
}, 1000);
</script>

enter image description here

Answer

JaredPar picture JaredPar · Aug 29, 2011

Try the following which will properly issue the count down for the selected values.

$(document).ready(function() {

  // Function to update counters on all elements with class counter
  var doUpdate = function() {
    $('.countdown').each(function() {
      var count = parseInt($(this).html());
      if (count !== 0) {
        $(this).html(count - 1);
      }
    });
  };

  // Schedule the update to happen once every second
  setInterval(doUpdate, 1000);
});

JSFiddle Example

Note: This will run the count down sequence on every element which has the countdown class. If you'd like to make it more restrictive to a single element you'll need to alter the selector from .countdown to something more restrictive. The easiest way is to add an id and reference the item directly.

<p id='theTarget'>15</p>

The JavaScript is a little more complex here because you'll want the timer to eventually shut off since there's not much chance, or use, of element with a duplicate id being added

$(document).ready(function() {

  var timer = setInterval(function() {

    var count = parseInt($('#theTarget').html());
    if (count !== 0) {
      $('#theTarget').html(count - 1);
    } else {
      clearInterval(timer);
    }
  }, 1000);
});

JSFiddle Example