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 data 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: 50px;
         color: #333;
      }
   </style>
</head>
<body>
   <script>
      const main=()=>{
         var time=new Date();
         const n=document.getElementById("container").innerHTML = time;
      }
      main();
   </script>
   <div class="container" id="container"></div>
   <button onclick="main()">click here</button>
</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 main() function is called to initialize the clock, and a button with an onclick attribute is included to allow the user to update the time.

Get The Individual Time

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 again after a certain period of time specified by the user.

Syntax

setInterval(<function name>, <time of interval>)

Example

<!DOCTYPE html>
<html>
<head>
   <title>Digital Clock</title>
</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;
         }
         if (minutes < 10) {
            minutes = "0" + minutes;
         }
         if (seconds < 10) {
            seconds = "0" + seconds;
         }
         let time = hours + ":" + minutes + ":" + seconds + " " + meridiem;
         document.getElementById("clockDisplay").innerHTML = time;
      }
      setInterval(updateClock, 1000);
   </script>
</body>
</html>

Explanation

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

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

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;
      }
   </style>
</head>
<body onload="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);">
   <div id="clockDisplay"></div>
</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 define the font family, size, color, and text alignment for the clock display.

Conclusion

Designing a digital clock using JavaScript is a useful exercise that can help improve your programming skills. By using setInterval or setTimeout functions, you can create a dynamic and visually appealing clock that accurately displays the current time in real time.

Updated on: 17-Apr-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements