Adding a live clock with the help of a form
Adding a live clock using forms is quite simple. The basic concept is to continuously write to a form field every 1 second, using the updated time from your own computer. Last section, we already discussed the essence of how to achieve calling a function continuously (by using the setTimeout function in a special manner) -now all we need to do is use that knowledge. First, lets see the date object again and some of its methods:
|getDate()||returns the day of the month|
|getDay()||Returns the day of the week|
|getHours()||returns the hour (Starts from 0-23)!|
|getMinutes()||returns the minutes|
|getSeconds()||returns the seconds|
|getMonth()||returns the month. (Starts from 0-11)!|
|getFullYear()||returns the year|
|getTime()||returns the complete time (in really weird format)|
You may want to cut and paste the below code and play around with it:
- Believe it or not, that's all there really is to it!
- Look at line 11. We first set "dn=AM". If the hours is > 12, meaning its afternoon, we set "dn=PM". If minutes/seconds is greater than 9, we added a "0" to it...why? because we want to pad it, just to make it look better. That's the basic structure of function show()
- The most important part, the
setTimeoutmethod, was already discussed prior to this page. Basically, this script is run every one second, which gives the illusion that the clock is actually ticking.
You, by no means, have to use a form when implementing your clock, but a form has many advantages: it is easy to add to your code, and more importantly, since all it does it "write" to a form, there is virtually no delay in time every second as it writes a new value to the text form. It is possible to implement a live clock that uses images. For an example of such, click here.
- Tutorial introduction- the date object
- Displaying a different image depending on the time of the day
- The setTimeout function
- Adding a live clock with the help of a form