JavaScript Clock Example

Question: How do I write a clock program in JavaScript?

Answer: A simple clock program would use the Date object to retrieve the current time every second (or, better yet, several times a second) and then display the time. The following code displays a clock on the browser's status bar and right here on the page (within the page element clockid):

 
Here is the function pgClock() that displays the clock on the page:
function pgClock() {
 var sTime=(new Date()).toString();
 document.getElementById('clockid').innerHTML =
   sTime.substring(0,3+sTime.lastIndexOf(':'));
 setTimeout('pgClock()',333);
}
pgClock();
And here is the function sbClock() showing the status-bar clock:
function sbClock() {
 var sTime=(new Date()).toString();
 self.status=sTime.substring(0,3+sTime.lastIndexOf(':'));
 setTimeout('sbClock()',333);
}
sbClock();

// JavaScript may or may not be allowed to write
// to the status bar, so sbClock might not work.

Copyright © 1999-2011, JavaScripter.net.