Feb 15, 2014

Make a Clock in Javascript



In this post we will create a simple clock that updates every second, and it is very easy to do and understand, it is a good way to go introducing us to the world of javascript.



Create the function

The first thing to do is open our favorite JavaScript editor (Sublime Text, NotePad + +, Dreamweaver, etc. ..) and we write:



function clock() {

         var dateNow = new Date();

         var hours = dateNow.getHours();
         var min = dateNow.getMinutes();
         var sec = dateNow.getSeconds();





The function "clock" is created and collect the information about the current date and time. Later the functions "get" keep the hour, minute and second collected in "dateNow". Then write:



        if(hours < 10) { hours = '0' + hours; }
if(min < 10) { min = '0' + min; }
if(sec < 10) { sec = '0' + sec; }



The variables have saved time but saved as a number, so if it is a single number does not include the 0 before, so we check that if a single digit, we add the 0 before. Then write:



var AmPm = ' am';
if(hours > 12)
{
  hours = hours - 12;
  AmPm = ' pm';
}


Just check whether it is higher or less than 12 for checking if it is "AM" or "PM" and save it in another variable. Then write:



var timeNow = hours+':'+min+':'+sec+AmPm;

document.getElementById("clock").innerHTML = timeNow

}



Save all in only one variable, and then we include the time in the div "clock" of the html. And now the function is completed. But we need update every second...



Update the clock

For the clock updating fence we need to use the function "setInterval" that what is call the function from time to time, in our case every 1000ms (1 sec) since the windows is loaded.



window.onload = function()
{
          setInterval(clock, 1000);
}




How insert the clock in HTML

We need to include the code in a script tag:



<script type="text/javascript">


function clock()
{

var dateNow = new Date();
var hours = dateNow.getHours();
var min = dateNow.getMinutes();
var sec = dateNow.getSeconds();

    if(hours < 10) { hours = '0' + hours; }
if(min < 10) { min = '0' + min; }
if(sec < 10) { sec = '0' + sec; }

var AmPm = ' am';
if(hours > 12)
{
  hours = hours - 12;
  AmPm = ' pm';
}

var timeNow = hours+':'+min+':'+sec+AmPm;

document.getElementById("clock").innerHTML = timeNow

}

window.onload = function()
{
  setInterval(clock, 1000);
}

      </script>


Or saved like a javascript file, and only referenced:



<script type="text/javascript" scr="address_of_file/clock.js"></script>


And then create the etiquetad <div id="clock"> </ div> at the place where we want to insert our clock in the HTML file.



Clock





Github Download

1 comment: