Monday, September 1, 2008

Javascript digital countdown clock

This is the conclusion of the digital clocks scripts. A countdown clock that is made in pretty much the same way as the others, but it countdowns a given time to zero. This has a lot of "real life" applications. IMHO, maybe the most appropriate usage is to tell the user how much session time he has left. How much time he has to spend waiting for that damn download to begin, etc., etc. Lots of the code is about the same as in the clock and the counter. Here it is:
window.onload = function()
{
 //create the clock just after the page has loaded
 draw_clock('countdown', '00:00:04');
}

function draw_clock(id, starting_time)
{
 //create the div that will hold the clock
 var clock = document.createElement('div');
 
 clock.id = id;
 
 //you can change the style of the clock ie to position it at a specific place on the page
 //i'll put this one approximately in the center of the page, but you can adjust that to fit your needs
 clock.style.position = 'absolute';
 clock.style.left = '50%';
 clock.style.top = '50%';
 clock.style.marginLeft = '-50px';
 clock.style.marginTop = '-20px';
 
 //keep the current time in an unexisting property (for the div element) - 'time'. Instead of declaring a global variable
 //you can use the current objects you have. This makes it a lot easier to remember what is what. If you are familiar 
 //with OOP, you can go even furher by declaring new javascript objects. Well, I will digg further into that OOP stuff later,
 //in another script :)
 clock.time = starting_time; 
 
 //get the current time and set it as div's innerHTML, using a function that formats it to look good on the page
 clock.innerHTML = get_clock_innerHTML(clock.time);

 //add the element to the page
 document.body.appendChild(clock);
 
 //set the timer which will update the clock. The interval can also be set to more or less than a second. 
 //If you need to update the time in another interval of time, say 15 seconds, you can use 15000 as the second argument to setInterval()
 window.countdown_interval = setInterval("clock_timer('"+id+"')", 1000);
}

function get_clock_innerHTML(time)
{
 //an array that stores the symbols which draw the good old-fashioned digital clock :) 
 //IMPORTANT: don't change the alignment or anything else on this array, cause this will cause the clock to look uglier, or even not work
 var digits = " _     _  _     _  _ _   _  _    "+
     "| | |  _| _||_||_ |_  | |_||_| . "+
     "|_| | |_  _|  | _||_| | |_| _| . "+
     "                                 ";

 //put the symbols inside a <pre> tag to make sure they will be displayed just like they are written in the array.
 //you can also change the style settings i've set
 var data = "<pre><span style='color: #181; background: #111; font-size: 10px;'>";

 //loop trough the four 'rows' of the array and display the appropriate symbols
 for(r = 0; r < 100; r += 33)
 {
  for(i = 0; i < time.length; i++)
  {
   for(c = (time[i])*3 + r , b = 0; b < 3; b++, c++)
   {
    if(isNaN(c))
     c = 10*3+r;

    data += digits[c];
   }
  }

  data += "<br />";
 }
 
 data += "</span></pre>";

 return data;
}

function clock_timer(id)
{
 var clock = document.getElementById(id);

 //get the current time and split it into hours minutes and seconds
 var tmp = clock.time.split(":");
 
 var hours   = tmp[0];
 var minutes = tmp[1];
 var seconds = tmp[2];
 
 //check what to decrement. If the seconds have reached zero we need to change either the minutes or both - minutes and hours
 if(seconds == 0)
 {
  //if the minutes have reached zero, decrement the hours and reset minutes and seconds.
  if(minutes == 0)
  {
   hours--;
   minutes = 59;
    seconds = 59;
  }
  else //just decrement the minutes and reset seconds
  {
   minutes--;
   seconds = 59;
  }
 }
 else //nothing interesting happend this last second - just decrement seconds and go on :)
  seconds--;
 
 //if the time has elapsed - call the function to destroy the counter and do someting else if you need to
 if(hours == 0 && minutes == 0 && seconds == 0)
  countdown_finished(id);
 
 //Save the new time in the appropriate form of HH:MM:SS
 clock.time = ((hours < 10) ? "0"+parseInt(hours) : hours)+
 ":"+ ((minutes < 10) ? "0"+parseInt(minutes) : minutes) +
 ":"+ ((seconds < 10) ? "0"+parseInt(seconds) : seconds);
 
 //update the clock with the new time
 clock.innerHTML = get_clock_innerHTML(clock.time);
}
That was easy, everything looks just like the counter, except we're counting down this time. Here is a little something that makes a lot of difference - the countdown_finished() function. It is called when the time has elapsed. This is the place where you can stop the countdown, alert() the appropriate message to the user, etc., etc. Do what you have to do when the time has elapsed. Here are some examples of what you might want to do:
  • The simpliest one - stop the countdown and tell the user the time has elapsed:
    function countdown_finished(id)
    {
     //clear the interval, cause the time has elapsed
     clearInterval(window.countdown_interval);
     
     alert('The time has elapsed!');
    }
    
    You can see a demo here and download the code from here.

  • Again, tell the user the countdown has finished, but this time remove the clock from the page:
    function countdown_finished(id)
    {
     //clear the interval, cause the time has elapsed
     clearInterval(window.countdown_interval);
     
     alert('The time has elapsed! It\' time to dissapear..');
     
     //get rid of the clock, we don't need it anymore ]:->
     document.body.removeChild(document.getElementById(id));
    }
    
    You can see a demo here and download the code from here.

  • Tell the user the time has elapsed and send him somewhere else:
    function countdown_finished(id)
    {
     //clear the interval, cause the time has elapsed
     clearInterval(window.countdown_interval);
     
     //tell the user he has had his time on that page..
     alert('Go away! You\'re not welcome anymore!');
     
     //and send him somewhere else
     window.location = "http://javascripthowtos.blogspot.com/";
    }
    
    You can see a demo here and download the code from here.

  • Redirect the user to the download he has waited for:
    function countdown_finished(id)
    {
     //clear the interval, cause the time has elapsed
     clearInterval(window.countdown_interval);
     
     //time has elapsed - redirect the user to the long waited download..
     alert('Ok, now you know how I look and what I can do. Now, download me!');
     
     //set the new location - the file to download
     window.location = "javascript digital countdown clock4.zip";
    }
    
    You can see a demo here and download the code from here.

  • After telling the user the time has elapsed - start the countdown again. This is also very usable if you wan't to do stuff over a period of time, and want to user to know how much time is left till 'stuff' happens.. :)
    function countdown_finished(id)
    {
     //clear the interval, cause the time has elapsed
     clearInterval(window.countdown_interval);
     
     alert('OK, one down! There goes another one!');
     
     //The countdown is dead. Long live the countdown! :)
     //create a new timeout for another countdown
     var new_timeout = Math.ceil(Math.random()*10);
     
     //add a leading zero if the number is just one digit
     if(new_timeout < 10)
      new_timeout = "0"+new_timeout;
     
     //create the new countdown clock, even use the same id as before, but use the new timeout
     draw_clock('countdown', "00:00:"+new_timeout); 
    }
    
    You can see a demo here and download the code from here.
The possibilities are endless - do whatever you need to do when the time has elapsed :)

No comments: