DEV Community

Cover image for Create a Simple Digital Clock Using HTML, CSS and JavaScript
Ryan
Ryan

Posted on

Create a Simple Digital Clock Using HTML, CSS and JavaScript

If you already possess the basic HTML, CSS and JavaScript skills, you know it's time to start building projects. It would be wise to get started building a few easy ones then moving up the ladder step by step. One such beginner-friendly projects would be a 'Digital Clock'

In this article, we'll learn to build a simple Digital Clock using some of the basic web development skills that you currently possess. We'll not work much on the UI of the clock, but in fact focus a lot on how to use JavaScript to put everything together to build the clock. so, let's get started.

First let's work on the markup. All we need is a single div element with a class of clock.

<div class="clock">16:20:35</div>
Enter fullscreen mode Exit fullscreen mode

This div element will contain the digits of the clock in the hh:mm:ss format. For now, I've simply added some placeholder digits, which will later be replaced dynamically with the current time using JavaScript. Now, let's add a few CSS styles.

@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;600&display=swap');

body{
  background: #000;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.clock{
  color: #fff;
  font-family: 'Orbitron', sans-serif;
  font-size: 6rem;
  letter-spacing: 1rem;
  font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

In the above styles, notice that we are using a custom Google font named Orbitron, which is best-suited for a digital clock. I've also added a few flex properties to the body simply to
vertically and horizontally center the clock. Lastly, a few styles have been added to the .clock div to slightly increase the font size and add a bit of a spacing. Below is a screen shot of what the clock looks like.

Image of a digital clock

Lastly, let's start working on the most important part, the JavaScript. First let's create a variable named clock. This variable will store the div element that has a class of clock.

let clock = document.querySelector('.clock')
Enter fullscreen mode Exit fullscreen mode

Now, we need to create a function to get the current hours, minutes and seconds. We'll name the function as updateTime.

function updateTime(){
  let hours = new Date().getHours();
  let minutes = new Date().getMinutes();
  let seconds = new Date().getSeconds(); 
}
Enter fullscreen mode Exit fullscreen mode

In the above function, the new Date() constructor gets the current date and time. The 3 methods getHours(), getMinutes(), getSeconeds() give us the current hour, minutes and seconds respectively. If we run this function in the console, we get:

screenshot of the function updateTime
In the above screenshot, you can see that the function returns hours, minutes and seconds as 12, 58 and 35. That's because the current time on my system is 12:58:35.

The next thing we need to do is simply insert the hours, minutes and the seconds in the div element which has the class of clock. For this, we'll be using the innerText property. Add the below line inside the function updateTime().

clock.innerHTML = `${hours}:${minutes}:${seconds}`;
Enter fullscreen mode Exit fullscreen mode

One additional thing we need to do is add an extra '0' if the digits are below 10. For instance if the time is 1:15:5, we want it to display 01:15:05. Add the below 3 lines of code in the function updateTime() just before the line clock.innerText = .....

hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
Enter fullscreen mode Exit fullscreen mode

In the first line of code above, all we are trying to say is 'if the hours is less than 10, which means, if it is anything between 0 to 9, add an extra 0 in front of it. Or else, keep it as it is'. We are doing the same thing with the minutes and the seconds.

So far, we have the below JavaScript code:

let clock = document.querySelector('.clock')

function updateTime(){
  let hours = new Date().getHours();
  let minutes = new Date().getMinutes();
  let seconds = new Date().getSeconds();

  hours = hours < 10 ? "0" + hours : hours;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;

 clock.innerHTML = `${hours}:${minutes}:${seconds}`;
}
Enter fullscreen mode Exit fullscreen mode

Now, all we need to do is simply display the time on our screen by calling the function updateTime() at the very end, outside the function block.

let clock = document.querySelector('.clock')

function updateTime(){
  let hours = new Date().getHours();
  let minutes = new Date().getMinutes();
  let seconds = new Date().getSeconds();

  hours = hours < 10 ? "0" + hours : hours;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;

 clock.innerHTML = `${hours}:${minutes}:${seconds}`;
}
updateTime();
Enter fullscreen mode Exit fullscreen mode

Here's what our clock looks like:

Image of a digital clock

But, our clock doesn't dynamically update yet. You need to refresh every time you want to check the updated time. So, to dynamically update our clock every second, we will be using the setTimeout() method. Add the below line inside the function block at the very end.

setTimeout(updateTime, 1000);
Enter fullscreen mode Exit fullscreen mode

This setTimeout() method will call the function updateTime every 1000 milliseconds, i.e. after every second. So, the final JavaScript code that we have is:

let clock = document.querySelector('.clock')

function updateTime(){
  let hours = new Date().getHours();
  let minutes = new Date().getMinutes();
  let seconds = new Date().getSeconds();

  hours = hours < 10 ? "0" + hours : hours;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;

 clock.innerHTML = `${hours}:${minutes}:${seconds}`;

setTimeout(updateTime, 1000);
}
updateTime();
Enter fullscreen mode Exit fullscreen mode

If you've done everything right, this is how your digital clock will look like:

A .gif image displaying a digital clock

In the above .gif image, you can notice that the clock is slightly shifting left and right, and that is because the digits do not have an even width. One of the easiest way to eliminate this issue is to remove the justify-content property given to the body element and give a margin-left to the clock div. I found 'margin-left:30%' seemed good enough to center the clock on larger displays.

So, that was a simple tutorial on how to create a digital clock using HTML, CSS and JavaScript. Hope you like it. Have a beautiful day.

Top comments (7)

Collapse
 
ant_f_dev profile image
Anthony Fung

Nice.

As you mentioned, the clock shifts slightly because the font characters are not the same width. If you narrow the category to Monospace, each character should have the same width. However, they don't look quite as cool as the font used in this article.

I also noticed that the seconds display sometimes jumps by two seconds. I'm guessing this is because the timeout is set to 1 second. The timeout duration guarantees that the callback won't be called before then, but may occur after; if it occurs a bit late (or the small delays build up), it could cause the seconds display to jump. One possible suggestion is to lessen the timeout below 1000ms. The JavaScript portion will end up doing more work, but could result in a smoother readout.

Collapse
 
ryandsouza13 profile image
Ryan

Thanks for the awesome tips. I'll surely keep that in mind.

Collapse
 
ant_f_dev profile image
Anthony Fung

No problem Ryan. Glad I could help.

Collapse
 
obere4u profile image
Nwosa Tochukwu

Nice

Collapse
 
ryandsouza13 profile image
Ryan

Thanks. Glad you liked it.

Collapse
 
giridhars profile image
Siddy Giridhar Reddy

setTimeout() will only execute the function only once after 1 second right?
I think setInterval() is good choice.

Collapse
 
ankitsaiyan profile image
Ankit Kumar

Hi Siddy,
If you notice setTimeout is being called inside the function which it is calling every 1000ms so it will run infinitely. You call it recursion with a delay.
setInterval will also work if we call it outside.