Javascript Clock

The current time is: (you must have JavaScript enabled to see the time)

 

 

The running clock above is an example of a JavaScript function that is triggered by the loading of the page, and is continuously re-executed over and over again after time delays of half a second.

The external JavaScript routine used here (named mytime(), which is in the external file clock.js) is basically the same as the time2.js code that we saw earlier. It appears in bold below. It is written as a function. A function is a block of JavaScript code that can be called by other JavaScript code. The function executes when called. (It is possible for the calling code to pass values to the function, and functions can return values to the calling code—niether of those things happens here.)

The body tag of this page looks like this: <body onload="mytime()">

When this page loads, the JavaScript command in the body tag is triggered and it calls the mytime() function, which is in an external file. The link to that external file is located at the END of the body (instead of in the head) for speed optimization reasons (although in this case, it's such a simple routine that it would not matter much). The mytime() routine then formats up the time in hours:minutes:seconds as a 12-hour am/pm format, and then it writes the result into the text content (the .innerHTML) of an element with id="timehere", which is a span in the paragraph that displays the time.

The last command in the function sets a timing event to trigger after 500 milliseconds (half of a second) which will trigger a call to mytime() again. And then the function ends. But half a second later, it is executed again to update the time...and it keeps doing this until the page is closed.

You will notice that the <span> with id="timehere" initially contains the text "(you must have JavaScript enabled to see the time)", but this text is replaced immediately when the page loads and the JavaScript executes for the first time, so you never see that text... but you would see it if your browser had JavaScript turned off.

Here is the function that is in the external file clock.js:

function mytime()
   {
   var d=new Date();
   ap="am";
   h=d.getHours();
   m=d.getMinutes();
   s=d.getSeconds();
   if (h>11) { ap = "pm"; }
   if (h>12) { h = h-12; }
   if (h==0) { h = 12; }
   if (m<10) { m = "0" + m; }
   if (s<10) { s = "0" + s; }
   document.getElementById('timehere').innerHTML=h + ":" + m + ":" + s + " " + ap;
   t=setTimeout('mytime()',500);
   }