Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery countdown timer

Tags:

Currently i have this code

setTimeout(function() { $('#hideMsg').fadeOut('fast'); }, 2000);

is it possible for me to put countdown timer for 2 seconds?

Like

<div id="hideMsg">
The entry you posted not valid.
This Box will Close In 2 Seconds
</div>

"This Box will Close In 2 Seconds" will automatically change to 2sec 1sec

like image 220
cicakman Avatar asked Sep 24 '10 07:09

cicakman


2 Answers

use setInterval instead of setTimeout, then with the combination of clearInterval

var sec = 2
var timer = setInterval(function() { 
   $('#hideMsg span').text(sec--);
   if (sec == -1) {
      $('#hideMsg').fadeOut('fast');
      clearInterval(timer);
   } 
}, 1000);

html

<div id="hideMsg">
The entry you posted not valid.
This Box will Close In <span>2</span> Seconds
</div>

crazy demo


Making it better.

var sec = $('#hideMsg span').text() || 0;
var timer = setInterval(function() { 
   $('#hideMsg span').text(--sec);
   if (sec == 0) {
      $('#hideMsg').fadeOut('fast');
      clearInterval(timer);
   } 
}, 1000);​

so that the time will depends on what is inside the <span>. For example, <span>2</span> is 2 seconds, <span>5</span> is 5 seconds, and <span>60</span> is 1 minute.

another crazy demo

like image 171
Reigel Avatar answered Sep 28 '22 14:09

Reigel


Note:

I didn't realize how similar this was to Reigel's answer until I read his answer. Basically, the only difference is that I use .delay() to hide the div instead of the interval. Different options...


If you put the initial number in a <span> this will count down to zero from whatever that number is:

$(function() {

               // Number of seconds counter starts at is what's in the span
    var timer, counter = $("#hideMsg span").text();

      // Delay the fadeout counter seconds
    $('#hideMsg').delay(counter * 1000).fadeOut('fast');

      // Update countdown number every second... and count down
    timer = setInterval(function() {

        $("#hideMsg span").html(--counter);
        if (counter == 0) { clearInterval(timer)};

    }, 1000);

});​

jsFiddle example


This makes use of jQuery's native .delay(), and it uses a setInterval() that stops when it gets to zero.

like image 27
Peter Ajtai Avatar answered Sep 28 '22 15:09

Peter Ajtai