JavaScript Digital Clock
In this article we are going to design a JavaScript based Digital Clock. Here we are see use a HTML Form to show our Digital Clock. Take a look below on piece of code…
<form name = "clockForm">
<input type="text" name="clock" size="10" class="frm" />
</form>
.frm {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 11px;
font-weight: bold;
color: #164BA0;
background-color: #D1D1D1;
border: 1px solid #83AAD3;
}
Now we have to add JavaScript which will generate Digital clock for us. Now we define a function Display() and going to call it through Window object supports methods setTimeout() to call same function after every 1000 milliseconds. The Window object supports methods for setting timers that we might use to perform a variety of functions. These methods include setTimeout() and clearTimeout(). The basic idea is to set a timeout to trigger a piece of script to occur at a particular time in the future. The general syntax is
timerId = setTimeout(script-to-execute, time-in-milliseconds);
As the Display() get called after every 1000 milliseconds recursively. A new value by Date() class gets stored in variable Today. Date class is mostly used for define and manipulate dates. You can get current time as well as date. You can also perform calculation based on date or times using date class. This is not a reserved word so you can declare your own variable or function called Date but if you do then you will not be able to use the Date class. See following piece of code for Display()
function display() {
var Today = new Date();
var hours = Today.getHours();
var min = Today.getMinutes();
var sec = Today.getSeconds();
var Time = ((hours > 12) ? hours - 12 :(hours == 0) ? 12 :hours);
Time += ((min < 10) ? ":0" : ":") + min;
Time += ((sec < 10) ? ":0" : ":") + sec;
Time += (hours >= 12) ? " PM" : " AM";
this.clockForm.clock.value = Time;
setTimeout("display()",1000);
}
display();
Our Clock will look like below image...

Here we are also converting 24 hour Clock into 12 hour with help of conditional operator. The conditional operator is another form of an “if” condition. It takes three parameters. The syntax looks like this: (Condition) ? val1: val2. If condition is true then it will return val1 otherwise val2.
example:
Please download Source Code and test it ...Source Code:
Download Source code for 'JavaScript Digital Clock'
Download
Also See:

written by geetha, April 08, 2008
written by Maheshwari, April 21, 2009
this.clockForm.clock.value = Time;
Solution :
document.clockForm.clock.value = Time;
written by Nejc, April 28, 2009
I know setTimeout works with system date and that's a problem... is there any possibility in javascript to use CPU clock for the "timeout".









