Tuesday, February 07, 2012
Blog Entries

Simplest JavaScript Clock for a Web Page

Nov 14

Written by:
11/14/2007 11:23 AM 

I was looking for some simple way of displaying the current date and time on a web page and having it updated each second. Most of the examples I found were overkill for what I needed.

Here's a complete listing for a web page that will display the clock as desired:

<html>
    <head>
        <title>Simplest JavaScript Clock</title>
        <script type="text/javascript">
            var tick;
            function stopClock()
            {
                clearTimeout(tick);
            }
            function updateClock()
            {
                var currentTime = new Date();
                document.getElementById('clock').innerHTML = currentTime.toString();
                tick = setTimeout("updateClock()", 1000);
            }
        </script>
    </head>
    <body onload="updateClock()" onunload="stopClock()">
        <div id="clock"></div>
    </body>
</html>
This displays text like this (in the Firefox 2 browser):

 Wed Nov 14 2007 11:10:18 GMT-0500 (Eastern Standard Time)

You can read more about JavaScript date and time functions to tweak the format of the string displayed.

Tags:
Categories:
Search Blog
Privacy Statement  |  Terms Of Use
Copyright 2007-2011 by Larry Daniele