jQuery countdown timer

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

Leave a Comment