Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a countdown timer with jQuery?

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

like image 949
Only Bolivian Here Avatar asked Dec 03 '22 07:12

Only Bolivian Here


2 Answers

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

  • http://jsfiddle.net/n24BP/

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

  • http://jsfiddle.net/bSe9E/
like image 132
JaredPar Avatar answered Dec 20 '22 03:12

JaredPar


HTML:

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

JS:

var count = document.getElementById('countdown');
timeoutfn = function(){
       count.innerHTML = parseInt(count.innerHTML) - 1;
       setTimeout(timeoutfn, 1000);
};
setTimeout(timeoutfn, 1000);

Fiddle: http://jsfiddle.net/wwvEn/

like image 42
Naftali Avatar answered Dec 20 '22 03:12

Naftali