Clock in JavaScript

Discussion in 'JavaScript and AJAX' started by pradeep, Oct 20, 2006.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Let us make a form based clock that displays time in the 24 hour format. We use the Date() object to get the hours, minutes, seconds of the day. setTimeoiut() evaluates an expression or calls a function after a certain amount of time, specified in milliseconds. We use setTimeout() to call the update() function every one second. So the clock in the text element is updated every second.

    HTML:
    <form name="Form1">
     <input type="text" size="8" name="Clock">
     </form>
     <script>
     function update()
     {
     	var today=new Date();
     	var hours=today.getHours();
     	var minutes=today.getMinutes();
     	var seconds=today.getSeconds();
     	if (hours<10)
     		hours="0"+hours;
     	if (minutes<10)
     		minutes="0"+minutes;
     	if (seconds<10)
     		seconds="0"+seconds;
     	document.Form1.Clock.value=hours+":"+minutes+":"+seconds;
     	setTimeout("update()",1000);
     }
     update();
     </script>
     
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice