JavaScript Clock Tutorial


Hey! So this quick tutorial will run you through creating a JavaScript clock that you see above. Why? Well it's not all too useful but it will teach you the basics of how JS works and how to manipulate time with it.



The HTML for this mini project is so simple, all you need is a tag, any tag. For this I chose to use the <code> tag because I liked its digital clock look.

The tag also needs an id attribute. This will allow us to access the HTML element with booth CSS and JavaScript.

<code id="clock">12:00:00</code>


The CSS for the clock is also really simple, so added two different declarations to the on selector. Firstly, color which changes the colour of the element selected and I also changed the font-size.

color: #184ea5; font-size: 100px; }

The JavaScript

Below is all of the JavaScript needed for the clock:

    var date = new Date();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();

    if(hours < 10)
        hours = '0' + hours;

    if(minutes < 10)
        minutes = '0' + minutes;

    if(seconds < 10)
        seconds = '0' + seconds;

    var clock = document.getElementById('clock');
    clock.innerHTML = hours + ':' + minutes + ':' + seconds;
}, 100);

setInterval(function(){ }, 100); This method calls the function set within it at specified intervals of milliseconds. This is what allows us too refresh the clock, in this case it happens every 100 milliseconds.

var date = new Date();

var hours = date.getHours();

var minutes = date.getMinutes();

var seconds = date.getSeconds();

The Date(); method allows you to use date and times. Start by creating the Date object by using: new date();. We use this object to set the current hours, minutes and seconds.

The if statements of the code is simply used to add a "0" to the beginning of any single digits.

We then set the element with the id of clock equal to the variable clock. Now using the .innerHTML property we update the clock element equal to the time variables we set earlier.

Further Reading

If you want to read further into JavaScript here are link to some great references:

Written by Rhys McClew

Why not check out my other posts? Or even learn a little more about me and go to the About Me page.

An image of Rhys McClew

Previous Post


  1. Noah 31st October 2018

    What’s up, just wanted to mention, I loved this post.
    It was helpful. Keep on posting!

Leave a Reply

© 2020 Rhys McClew

Theme by Anders Norén