Javascript TUTORIAL


Javascript Timer




Let us make a form based clock that displays time in the 24 hour format.



  1. <form name="Form1">
  2. <input type="text" size="8" name="Clock"> </form>
  3. <script>
  4. function update()
  5. {
  6. var today=new Date();
  7. var hours=today.getHours();
  8. var minutes=today.getMinutes();
  9. var seconds=today.getSeconds();
  10. if (hours<10)
  11. hours="0"+hours;
  12. if (minutes<10)
  13. minutes="0"+minutes;
  14. if (seconds<10)
  15. seconds="0"+seconds;
  16. document.Form1.Clock.value=hours+":"+minutes+":"+seconds;
  17. setTimeout("update()",1000);
  18. }
  19. update();
  20. </script>




Save the file as say timer.htm. If you open the file in a browser it will produce the following.



Explanation



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.

You can try this example online at the link below, which will open in a new window.

Javascript Timer Example

Here is another example that displays the characters of a string at defined interval ( like in typewriter).



  1. <form name="Form1">
  2. <input type="text" size="20" name="Clock"> </form>
  3. <script>
  4. var str="HELLO WORLD";
  5. var strtodisplay="";
  6. var i=0;
  7.  
  8. function update()
  9. {
  10. document.Form1.Clock.value=strtodisplay;
  11. strtodisplay = strtodisplay + str.charAt(i);
  12. i++;
  13. if ( i<=str.length)
  14. setTimeout("update()",100);
  15. }
  16. update();
  17. </script>


You can try this example online at the link below, which will open in a new window.

Javascript Timer Example