Javascript  HTML  Web Development  
   Technology    Programming

Build a Simple Digital Clock with JavaScript

 OCTOBER 7, 2020   by nemo011

Building a digital clock using JavaScript can be an excellent project for a beginner to understand the basic concepts of JavaScript. Creating this will help you know about accessing the DOM, adding activity to them and much more.

So, let's start.

What should you know before you start?

  • Basic HTML

  • Basic CSS

  • Little Knowledge of JavaScript

What will we learn?

  • Creating Variables in JS

  • Accessing DOM in JS

  • Adding Properties to the DOM

Here’s the preview of what we are going to build today.

As you can see, we have a clock which is centred. To achieve this, we'll be using CSS flexbox here. If you are not familiar with flexbox, check this our 2-part flexbox series.

HTML Code:

Our HTML is a single line of code. We'll just add a container in which our clock will show up.

<!DOCTYPE html>
<html lang="en">
		<meta charset="UTF-8"/>
		<meta name="viewport" content="width=,initial-scale="/>
		<link href="[email protected]&display=swap" rel="stylesheet"/>
		<div id="clock"></div>

Look at the code. The only thing we are adding except the boilerplate HTML is a div with an id of clock and a font using Google Fonts. We'll target this div to show up the digital clock using JavaScript.

CSS Code:

In our CSS code we will provide styling for the body of our HTML page and for the clock.

body {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
	font-family: "Lato", sans-serif;

#clock {
	height: 100vh;
	width: 100%;
	background-color: #14080e;
	color: #e9eb9e;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 50px;

Our CSS is also straightforward. First, we'll reset our page with the margin:0, padding:0 property. We are also adding the font-family to the body. Next, we are styling our clock div. The height: 100vh will give the id a height of the complete viewport. We are also giving it a width of 100%. Then, we are adding a background color and a text color to it using the background-color and color property respectively.

We want our clock to be centered of the page. To achieve this, we'll take help of the CSS flexbox. First of all, we are invoking flexbox using the display: flex property, then to center the element through the main axis, we are using the justify-content:center property and to center it along the cross-axis, we are using the align-items:center property. And, finally, we are giving a font-size of 100px. And we are done with the CSS.

Now comes the most crucial part.


Before writing the JavaScript part, let’s understand a few basics that we’ll need here.

The Date Object:

The Date object is a JavaScript object that represents the date and time. Inside the object, the date is stored as a number in milliseconds since 1st January 1970.

To create the Date object, we use the Date constructor. Creating a new Date object will return the current date and time.


let date = new Date();


Mon Oct 05 2020 22:28:08 GMT+0530 (India Standard Time)

The output will change depending on your locale.

This Date object has multiple methods on it. These methods are used to extract different values from the object. For example, to extract the hour from the object, we have a method called getHours().

Similarly, getMinutes() method will give us the minutes, and the getSeconds() will provide the seconds. Another thing to note while using Date object is that it'll return the hour in 24-hour format.

Now, let’s start writing the JavaScript part.

We’ll be creating the whole code inside a function. We are using the ES6 arrow functions here. If you don't know what JavaScript arrow functions are, here's an awesome article about it.

let clock = () => {
  let date = new Date();
  let hrs = date.getHours();
  let mins = date.getMinutes();
  let secs = date.getSeconds();
  let time = `${hrs}:${mins}:${secs}`
  // log the time in console
// call the clock function

As you can see from the above code, we are storing the Date object inside a variable called date and then calling different methods over the object to get the distinct values. We are holding the values inside variables. We are creating another variable called time, where we are concatenating the hours, minutes and seconds using template literals. To check if we are getting the correct output, we are console logging the time variable.

Our clock is almost ready. But it is in a 24-hour format for now. To make it a 12-hour clock, we’ll be taking the help of conditional statements. But before writing the condition, we’ll declare another variable to keep track of AM or PM. Let's call it period here.

The Condition

let period = "AM";
if (hrs == 0) hrs = 12;

if (hrs > 12) {	    
	hrs = hrs - 12;	    
	period = "PM";	  

What are we doing in the condition? If hours is 0 (i.e., the midnight 0th hour), we set the hrs to 12, and if it's greater than 12, we calculate the hour using hrs - 12 and also set the period to PM. So, our clock is ready for 12-hour format. To make it look better, we’ll also be adding a zero in front of the numbers whenever the number is less than 10. We’ll use JavaScript ternary operator for that. We can also do it using conditionals, but it would require us to write more code.

hrs = hrs < 10 ? `0${hrs}` : hrs;
mins = mins < 10 ? `0${mins}` : mins;
secs = secs < 10 ? `0${secs}` : secs;

As you can see, whenever the number is less than 10, we are concatenating the number with a 0 in front of it, and otherwise, we set the value that we are getting. Now, how do we show it in the browser? Here comes the use of DOM.

 document.getElementById("clock").innerText = time;

First, we are targeting the DOM with the help of the div ID of the clock, and then we are assigning an inner text to the div using the innerText setter. We are setting the time variable as the inner text. We’ve also added the period to the time variable.

So, our clock is almost ready. But if you check the browser now, you’ll find that the clock is stuck in a particular time. It is not changing. Why? Because the Date object is storing the value once and not changing it. To solve this issue, we’ll need a JavaScript function called setInterval. This function evaluates a function repeatedly after a given time. We will pass two arguments into setInterval for this example, the first argument will be the function that has to be executed, and the second argument is the time after which we want to execute it again and again.

setInterval(clock, 1000)

The setInterval function takes time as milliseconds. We want to execute the clock function after every 1second. So, we are passing clock as the first parameter and 1000(i.e., 1 second) as the second parameter.

And our clock is ready.

Final JavaScript Code

let clock = () => {
  let date = new Date();
  let hrs = date.getHours();
  let mins = date.getMinutes();
  let secs = date.getSeconds();
  let period = "AM";
  if (hrs == 0) {
    hrs = 12;
  } else if (hrs >= 12) {
    hrs = hrs - 12;
    period = "PM";
  hrs = hrs < 10 ? "0" + hrs : hrs;
  mins = mins < 10 ? "0" + mins : mins;
  secs = secs < 10 ? "0" + secs : secs;

  let time = `${hrs}:${mins}:${secs}:${period}`;
  document.getElementById("clock").innerText = time;
  setTimeout(clock, 1000);


Now that we know how to implement this. Below we have a live working code for this. Try to run it to see the code in action and try making changes to the code to customize the clock.


I hope you learnt something new from this article. If you enjoyed it, do check the building a theme switcher article.


Subscribe and receive amazing posts directly in your inbox.