Simple clock using standard Javascript

Ah the challenge for making your first clock in Javascript, I remember those days. It seems like such a daunting task at first, but it’s really quite simple.

This code creates a fully functional clock using only Javascript and HTML. I’ve only checked it in Firefox and Chrome, but it’s simple enough it should work in most major browsers. It will output the hours, minutes and seconds in a 24-hour time format.

Try challenging yourself and modifying the code to output a 12-hour clock with AM/PM instead.

<!DOCTYPE html>
<html>
    <head>
        <title>The Time</title>
        <script type="text/javascript">
            // This function gets the current time and injects it into the DOM
            function updateClock() {
                // Gets the current time
                var now = new Date();
 
                // Get the hours, minutes and seconds from the current time
                var hours = now.getHours();
                var minutes = now.getMinutes();
                var seconds = now.getSeconds();
 
                // Format hours, minutes and seconds
                if (hours < 10) {
                    hours = "0" + hours;
                }
                if (minutes < 10) {
                    minutes = "0" + minutes;
                }
                if (seconds < 10) {
                    seconds = "0" + seconds;
                }
 
                // Gets the element we want to inject the clock into
                var elem = document.getElementById('clock');
 
                // Sets the elements inner HTML value to our clock data
                elem.innerHTML = hours + ':' + minutes + ':' + seconds;
            }
        </script>
    </head>
    <!--
        This is the key to making the clock function.
        When the page loads, it calls the javascript function "setInterval()",
        which will call our function "updateClock()" once every 200 milliseconds.
    -->
    <body onload="setInterval('updateClock()', 200);">
        <!-- This is the container for our clock, it can be any HTML element. -->
        <h1 id="clock"></h1>
    </body>
</html>

4 thoughts on “Simple clock using standard Javascript

  1. Great little script.

    I would like to use this to show the time in other timezones.
    How can i change the time, say +3 hours from local time?

    Thx.

  2. Worked great, thanks a bunch! I wanted it in 12hr format, seems like are a thousand ways to do it, but I came up with:

    if (hour > 12) {
    hour = hour – 12;
    }

    thanks again

Comments are closed.