How to Design Digital Clock using JavaScript?

Dealing with time is one of the most common concepts of web developers. Whether to schedule time for the subscription period or schedule email sending requires developers to deal with the time. In this article, we will learn how to design a digital clock using JavaScript.

Get The Time On Clicking The Button

We can achieve the same operation using multiple logic and codes. First, in this section, we shall learn how to design a digital clock that shows the time when the user clicks on the button.

Follow the steps to achieve the step ?

  • First, create a button that the user can click to see the time.

  • Next, create an onClick listener on the button, and upon clicking call a function say main.

  • Under the main function define a date object.

  • Update the text(inner HTML) of the desired target element to display the time.

Example

<!DOCTYPE html>
<html>
<head>
   <title>Digital Clock</title>
   <style>
      body {
         font-family: Arial, Helvetica, sans-serif;
         text-align: center;
         margin-top: 100px;
         font-size: 30px;
         color: #333;
      }
      button {
         font-size: 18px;
         padding: 10px 20px;
         margin-top: 20px;
         cursor: pointer;
      }
   </style>
</head>
<body>
   <div id="container">Click the button to see time</div>
   <button onclick="showTime()">Show Current Time</button>
   
   <script>
      function showTime() {
         var time = new Date();
         document.getElementById("container").innerHTML = time.toLocaleTimeString();
      }
   </script>
</body>
</html>

Explanation

  • This code creates a digital clock in HTML using JavaScript. It includes a script that creates a new Date object and sets it to the time variable.

  • The time is then displayed in a container element with an id of the container. The showTime() function is called when the user clicks the button to display the current time.

Create An Auto-Updating Digital Clock

In the previous example, we saw how to get the time when the user clicks on the button. However, we may also need to dynamically change the time and update it in our web application. JavaScript provides us with a method called setInterval which calls the function repeatedly after a certain period of time specified by the user.

Syntax

setInterval(function, milliseconds)

Example

<!DOCTYPE html>
<html>
<head>
   <title>Digital Clock</title>
   <style>
      body {
         font-family: Arial, Helvetica, sans-serif;
         text-align: center;
         margin-top: 100px;
         font-size: 40px;
         color: #333;
         background-color: #f0f0f0;
      }
      #clockDisplay {
         background-color: #000;
         color: #00ff00;
         padding: 20px;
         border-radius: 10px;
         display: inline-block;
         font-family: 'Courier New', monospace;
      }
   </style>
</head>
<body>
   <div id="clockDisplay"></div>
   
   <script>
      function updateClock() {
         let date = new Date();
         let hours = date.getHours();
         let minutes = date.getMinutes();
         let seconds = date.getSeconds();
         let meridiem = "AM";
         
         if (hours > 12) {
            hours -= 12;
            meridiem = "PM";
         }
         if (hours === 0) {
            hours = 12;
         }
         
         // Add leading zeros
         if (minutes < 10) {
            minutes = "0" + minutes;
         }
         if (seconds < 10) {
            seconds = "0" + seconds;
         }
         
         let time = hours + ":" + minutes + ":" + seconds + " " + meridiem;
         document.getElementById("clockDisplay").innerHTML = time;
      }
      
      // Update clock immediately and then every second
      updateClock();
      setInterval(updateClock, 1000);
   </script>
</body>
</html>

Explanation

  • This code creates a digital clock in HTML using JavaScript. It includes an updateClock() function that retrieves the current date and formats it into hours, minutes, seconds, and meridiem.

  • The setInterval() method is used to update the clock every second (1000 milliseconds). The time is displayed in a container element with an id of clockDisplay.

Compact Digital Clock Implementation

We can make the above code even more concise. Since the Date() method gives the time containing the hour, minute, seconds, etc we can perform numeric operations on them to get the desired result.

Example

<!DOCTYPE html>
<html>
<head>
   <title>Digital Clock</title>
   <style>
      body {
         font-family: Arial, Helvetica, sans-serif;
         text-align: center;
         margin-top: 100px;
         font-size: 50px;
         color: #333;
         background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
         color: white;
         min-height: 100vh;
         margin: 0;
         display: flex;
         align-items: center;
         justify-content: center;
      }
      #clockDisplay {
         background-color: rgba(255, 255, 255, 0.1);
         padding: 30px;
         border-radius: 15px;
         backdrop-filter: blur(10px);
         border: 1px solid rgba(255, 255, 255, 0.2);
      }
   </style>
</head>
<body>
   <div id="clockDisplay"></div>
   
   <script>
      setInterval(() => {
         let date = new Date();
         let time = (date.getHours() % 12 || 12) + ':' + 
                   ('0' + date.getMinutes()).slice(-2) + ':' + 
                   ('0' + date.getSeconds()).slice(-2) + ' ' + 
                   (date.getHours() >= 12 ? 'PM' : 'AM');
         document.getElementById('clockDisplay').textContent = time;
      }, 1000);
      
      // Initialize clock immediately
      document.getElementById('clockDisplay').textContent = 
         new Date().toLocaleTimeString([], {hour12: true});
   </script>
</body>
</html>

Explanation

  • This is an HTML document with embedded CSS and JavaScript code. It displays a digital clock that updates every second using the setInterval method in JavaScript.

  • The clock displays the current time in a 12-hour format with AM/PM indication. The CSS styles create a modern gradient background with a glass-morphism effect for the clock display.

Key Features of Digital Clock

When creating digital clocks, consider these important aspects:

  • Time Format: Choose between 12-hour (AM/PM) or 24-hour format

  • Leading Zeros: Add zeros for single-digit minutes and seconds (e.g., 09:05:03)

  • Update Frequency: Use setInterval with 1000ms for real-time updates

  • Initial Display: Call the update function immediately to avoid blank display

Conclusion

Designing a digital clock using JavaScript is a practical exercise that demonstrates time manipulation and DOM updates. By using setInterval() function, you can create dynamic, auto-updating clocks with custom styling and formatting options.

Updated on: 2026-03-15T23:19:01+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements