Javascript countdown timer

Javascript countdown timer

Posted in: javascript by musiitwa joseph 2015-03-02 at 12:00:00

image for Javascript countdown timer setTimeout() method accepts two arguments: the code to execute and the number of time in milliseconds. The first argument can be either a string containing javascript code or a function, in this case its a function. The second argument, the number of milliseconds to wait before attempting to execute the code. Most of the times we deal with seconds and 1second = 1000milliseconds.

When the setTimeout() method is called, it returns a numeric ID that can be used to cancel the setTimeout() from executing the code. This is done by passing the ID as an argument of clearTimeout().


window.onload = function (){
_("timer").style.display = "none";//hiding the timer

function _(x){
return document.getElementById(x);

function ds(i){//appends a zero to digits btn 0-9
return "0"+i;
return i;

function calculateTotalSeconds(){
var timeString,splittedHours,splittedMins,splittedSecs;
if(splittedSecs >= 60||splittedMins >= 60*60||splittedHours >= 60*60*60){
alert("60 or greater than 60 is not allowed for hours or minutes or seconds");
return 'a';
//getting the time from the input field and then split
timeString = _("time").value.split(":");//forms an array timeString

//1hour = 60minutes and 1minute = 60seconds, so we multiple hours with 60*60
splittedHours = parseInt(timeString[0])*60*60;

//1minute = 60seconds, so we multiple minutes with 60
splittedMins = parseInt(timeString[1])*60;

//no conversion needed, this is already in seconds.
splittedSecs = parseInt(timeString[2]);

//sum the converted minutes and hours to seconds
return (splittedSecs + splittedMins + splittedHours);


function timerComputation(totalSeconds){

var mins=0, hrs=0, secs;

_("timer").style.display = "block";
_("userInput").style.display = "none";

diving the total seconds into minutes and hours which should before
less than 60.
var seconds = totalSeconds/60;
if(seconds < 1){
secs = totalSeconds;
mins = Math.floor(totalSeconds/60);//total minutes from seconds
secs = totalSeconds - (mins*60);
if(mins >= 60){
hrs = Math.floor(mins/60);//total hours from minutes
mins = mins - (hrs * 60);

if(totalSeconds < 0){
alert("Time out !!!!");
_("timer").style.display = "none";
_("userInput").style.display = "block";
//ds() appends a zero to digits btn 0-9
_("timer").innerHTML = ds(hrs)+":"+ds(mins)+":"+ds(secs);

//decrementing the total seconds;

//recursive function
setTimeoutID = setTimeout('timerComputation('+totalSeconds+')', 1000);

alert("Invalid time"); //if empty or contains a non numeric character



Leave a comment

Fields with * are required
Your email address will not be displayed
3 + 2 =