Code for a simple JavaScript countdown timer?
var count=30;var counter=setInterval(timer, 1000); //1000 will run it every 1 secondfunction timer(){ count=count-1; if (count <= 0) { clearInterval(counter); //counter ended, do something here return; } //Do code for showing the number of seconds here}
To make the code for the timer appear in a paragraph (or anywhere else on the page), just put the line:
<span id="timer"></span>
where you want the seconds to appear. Then insert the following line in your timer()
function, so it looks like this:
function timer(){ count=count-1; if (count <= 0) { clearInterval(counter); return; } document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling}
I wrote this script some time ago:
Usage:
var myCounter = new Countdown({ seconds:5, // number of seconds to count down onUpdateStatus: function(sec){console.log(sec);}, // callback for each second onCounterEnd: function(){ alert('counter ended!');} // final action});myCounter.start();
function Countdown(options) { var timer, instance = this, seconds = options.seconds || 10, updateStatus = options.onUpdateStatus || function () {}, counterEnd = options.onCounterEnd || function () {}; function decrementCounter() { updateStatus(seconds); if (seconds === 0) { counterEnd(); instance.stop(); } seconds--; } this.start = function () { clearInterval(timer); timer = 0; seconds = options.seconds; timer = setInterval(decrementCounter, 1000); }; this.stop = function () { clearInterval(timer); };}
So far the answers seem to rely on code being run instantly. If you set a timer for 1000ms, it will actually be around 1008 instead.
Here is how you should do it:
function timer(time,update,complete) { var start = new Date().getTime(); var interval = setInterval(function() { var now = time-(new Date().getTime()-start); if( now <= 0) { clearInterval(interval); complete(); } else update(Math.floor(now/1000)); },100); // the smaller this number, the more accurate the timer will be}
To use, call:
timer( 5000, // milliseconds function(timeleft) { // called every step to update the visible countdown document.getElementById('timer').innerHTML = timeleft+" second(s)"; }, function() { // what to do after alert("Timer complete!"); });