How to Design Digital Clock Using JavaScript?

JavaScript provides a variety of methods to build state of the art web-based components to enhance the interactiveness of the website. Digital clock is the key element of any website that would show the current time on the specific part of the webpage.

In today’s guide, we will demonstrate the way to create a digital clock using JavaScript.

How to Design a Digital Clock Using JavaScript?

You would have observed digital clocks on most of the websites. Have you ever thought, how they are created? It is JavaScript which enables you to put live digital clocks on the webpages. Let’s see how you can create it.

Before getting into details, you must know the working of few built in JavaScript methods that will be used in this example. The Date() method is the key component of creating a digital clock, as it contains the date, time, year, etc information. Moreover, the following methods will also be used:

  • getSeconds(): to obtain the seconds.
  • getMinutes(): to retrieve the minutes.
  • getHours(): to get the hour.


The following example code represents the creation of a digital clock using JavaScript.


<!DOCTYPE html>


<body onload="startTime()">

<h1>Welcome to the Digital Clock using JavaScript</h1>

<div id="txt"></div>


functionstartTime() {
const date = newDate();
let secs = date.getSeconds();   // Store seconds in secs variable
let mints = date.getMinutes(); //  Minutes are stored in mints variable
let hrs = date.getHours();  //  variable hrs stores the number of hours
  secs = Time(secs);
  mints = Time(mints);
document.getElementById('txt').innerHTML =  hrs + ":" + mints + ":" + secs;
  setTimeout(startTime, 500);
functionTime(i) {
if (i <10) {i = "0" + i};  // add zero in front of numbers < 10
return i;




The description of the code is as follows:

  • The startTime() method is defined in which you extract the current date by utilizing the Date() method.
  • Furthermore, the object of the Date() method is used with getSeconds(), getHours(), and getMinutes() methods to extract the seconds, hours, and minutes.
  • Afterwards, the Time() method is utilized to place zero on the left side of the number if the number is less than zero.


The output represents that a simple digital clock is displayed on the webpage which shows the current time.


A digital clock can be created by using the Date() method and applying the object of the Date() method on the getSeconds(), getMinutes(), and getHours() methods. In this article, user learned to design a digital clock in JavaScript. The getSeconds(), getMinutes(), and getHours() methods are used to extract the seconds, minutes, and hours from the Date method.

About the author

Syed Minhal Abbas

I hold a master's degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.