Home  »  Articles  »  Java Script  »

Countdown Timer in JavaScript

 Posted By : Manoj SahooPosted Date : 15/11/2010 02:00:19 PM Category : Java Script Points : 5 (Rs 1.00)

Description:

This Code Snippet demonstrates to set countdown timer in any web page. It displays days,hours, minutes and seconds remaining.

Technical Features:

1. Uses HTML controls and JavaScript
2. Calculates time remaining of countdown session through JavaScript function
3. Demonstrates JavaScript function and if…else
4. Show the error message when complete

Code

var day = '1';   // day of month or + day offset
var hour = 14;    // 0 through 23 for the hour of the day
var min=10;   // 0 through 59 for the minute of hour
var second=15;  //0 through 59 for the second of minute
var lab = 'cd';  // id of the entry on the page where the counter is to be inserted
function start() {displayCountdown(setCountdown(day,hour,min,second),lab);}
loaded(lab,start);
var pageLoaded = 0; window.onload = function() {pageLoaded = 1;}
function loaded(i,f) {if (document.getElementById && document.getElementById(i) != null) f(); else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}
function setCountdown(day,hour,min,second)
{
var c = setC(day,hour,min,second);
return c;
}
function setC(day,hour,min,second)
{
return Math.floor((((day*24+hour)*60+min)*60+second));
}
function displayCountdown(countdn,cd)
{
if (countdn < 0)
document.getElementById(cd).innerHTML = "Sorry, you are too late.";
else
{
var secs = countdn % 60;
if (secs < 10)
secs = '0'+secs;
var countdn1 = (countdn - secs) / 60;
var mins = countdn1 % 60;
if (mins < 10)
mins = '0'+mins;
countdn1 = (countdn1 - mins) / 60;
var hours = countdn1 % 24;
var days = (countdn1 - hours) / 24;
document.getElementById(cd).innerHTML = days+' days  &     '+hours+' Hrs : '+mins+' Mins : '+secs +' Sec';
setTimeout('displayCountdown('+(countdn-1)+',\''+cd+'\');',999);
}
}

 

You put the above code in count.js file

Then place this in html file’s head section to see the effect.

<html>
<head>
<script type="text/javascript" src="count.js">
</script>
</head>
<body>
<span id="cd"></span>
</body>
</html>

Thank you.

Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.