Digital Clock In JavaScript
We can display a clock that will show the local time of the client computer using JavaScript. Note this will display the time from the user’s computer, not the server.
We have seen in this tutorial the Date object and how to display the current date and time. Here we will try to display the date and time in real-time or by using the setTimeout function. This function we used to trigger the display function with a refresh rate of one second (1s).
[st_adsense]
Digital Clock In JavaScript
<html> <head> <script type="text/javascript"> function refresh(){ var t = 1000; // refresh in milliseconds setTimeout('showDate()',t) } function showDate() { var date = new Date() var h = date.getHours(); var m = date.getMinutes(); var s = date.getSeconds(); if( h < 10 ){ h = '0' + h; } if( m < 10 ){ m = '0' + m; } if( s < 10 ){ s = '0' + s; } var time = h + ':' + m + ':' + s document.getElementById('clock').innerHTML = time; refresh(); } </script> </head> <body onload=showDate();> <span id='clock' style="background-color:#1C1C1C;color:silver;font-size:40px;"></span> </body> </html>
Result |
---|