Jump to Real's How-to Main page

Have a simple on-screen clock

<SCRIPT>
 var tick;
 function stop() {
   clearTimeout(tick);
   }
 function simpleClock() {
   var ut=new Date();
   var h,m,s;
   var time="        ";
   h=ut.getHours();
   m=ut.getMinutes();
   s=ut.getSeconds();
   if(s<=9) s="0"+s;
   if(m<=9) m="0"+m;
   if(h<=9) h="0"+h;
   time+=h+":"+m+":"+s;
   document.sclock.stime.value=time;
   tick=setTimeout("simpleClock()",1000);    
   }
</SCRIPT>

<BODY  onLoad="simpleClock();" onUnload="stop();"> 

<FORM NAME="sclock">
<INPUT TYPE="text" NAME="stime" SIZE="13">
</FORM>

The following version (submitted by dhoang, thanks!) is using a SPAN instead of a FORM. Using this technique, it is easy to insert the clock in a paragraph : clock, the look is much better than when we were using a FORM!. The new script is

<SCRIPT>
 var tick;
 function stop() {
   clearTimeout(tick);
   }
 function simpleClock() {
   var ut=new Date();
   var h,m,s;
   var time="        ";
   h=ut.getHours();
   m=ut.getMinutes();
   s=ut.getSeconds();
   if(s<=9) s="0"+s;
   if(m<=9) m="0"+m;
   if(h<=9) h="0"+h;
   time+=h+":"+m+":"+s;
   document.getElementById('clock').innerHTML=time;
   tick=setTimeout("simpleClock()",1000);    
   }
</SCRIPT>

<BODY  onLoad="simpleClock();" onUnload="stop();"> 


<p>My clock : <span id="clock">clock</span>

If you find this article useful, consider making a small donation
to show your supportfor this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]