Table of contents
1.
Introduction
2.
Implementation
2.1.
24 Hour clock using javascript
2.2.
12 Hour clock using javascript
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Implement digital watch/Timer in vanilla JS and show time in HH:MM:SS format

Author Malay Gain
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Using a digital watch or timer on any website or web application is often necessary when we need to track time. But it is not at all a hard task to add a real-time watch on a website by just using vanilla js.  Here we will be implementing a real-time digital clock using vanilla js. Though some sort of HTML and CSS will be used for rending the webpage, we will be particularly focusing on Javascript code.

 

Implementation

24 Hour clock using javascript

 

HTML file

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        
        <title>Digital Watch</title>
    </head>
    <body>
        <!-- representing time "HH:MM:SS" format.-->
        <h1 id="time"></h1>
        <!--linking the external JavaScript file -->
        <script src="./script.js"></script>
    </body>
</html>

Js file

setInterval(function(){

    // GET TIME STRING
    var time = getCurrentTime();
    // Replace the current text
    document.getElementById('time').innerText = time;
},1000);

function getCurrentTime(){
    // getting the current time using Date() constructor
    var dateObj = new Date();
    // Serialise clock time
    var time = {
        hours:dateObj.getHours(),
        minutes:dateObj.getMinutes(),
        seconds:dateObj.getSeconds(),
       
    }
    
    
    // Prepend a 0 on the hours to make double digits
    if(time.hours < 10){
        time.hours = '0'+time.hours
    }
    // Prepend a 0 on the Minutes to make double digits
    if(time.minutes < 10){
        time.minutes = '0'+time.minutes
    }
    // Prepend a 0 on the Seconds to make double digits
    if(time.seconds < 10){
        time.seconds = '0'+time.seconds
    }

    // Formatting the clock time as a string "HH:MM:SS"
    return time.hours + ':' + time.minutes + ':' + time.seconds + ' '  
}
You can also try this code with Online Javascript Compiler
Run Code

Explanation

In the above code, we have implemented getCurrentTime() which returns current time in HH:MM:SS format. This function uses Date() constructor which returns browser’s date along with time zone. But date object is static , so we need to keep on updating for getting current time at every instance. We have defined an object time  with three properties - hours, minutes, seconds. We extract hours, minutes and seconds from dateObj using getHours(), getMinutes(), getSeconds() methods respectively.

If hours, minutes or seconds is a single digit number, we prepend 0 before that digit.

As the date object is static, we have used setInterval(function, milliseconds) for evaluating the  getCurrentTime() function at the interval of every second (1000ms) to get the current time at every second.

12 Hour clock using javascript

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        
        <title>Digital Watch</title>
    </head>
    <body>
        <!-- representing time "HH:MM:SS" format.-->
        <h1 id="time"></h1>
        <!--linking the external JavaScript file -->
        <script src="./script.js"></script>
    </body>
</html>
setInterval(function(){

    // GET TIME STRING
    var time = getCurrentTime();
    // Replace the current text
    document.getElementById('time').innerText = time;
},1000);

function getCurrentTime(){
    // getting the current time using Date() constructor
    var dateObj = new Date();
    // Serialise clock time
    var time = {
        hours:dateObj.getHours(),
        minutes:dateObj.getMinutes(),
        seconds:dateObj.getSeconds(),
        session: 'AM'
    }
    
    if(time.hours > 12){
        time.hours -= 12;
        time.session = 'PM'
    }
    
    // Prepend a 0 on the hours to make double digits
    if(time.hours < 10){
        time.hours = '0'+time.hours
    }
    // Prepend a 0 on the Minutes to make double digits
    if(time.minutes < 10){
        time.minutes = '0'+time.minutes
    }
    // Prepend a 0 on the Seconds to make double digits
    if(time.seconds < 10){
        time.seconds = '0'+time.seconds
    }

    // Formatting the clock time as a string "HH:MM:SS"
    return time.hours + ':' + time.minutes + ':' + time.seconds + ' ' + time.session 
}
You can also try this code with Online Javascript Compiler
Run Code

Explanation

To turn the 24-hour clock into a 12-hour clock, we need to subtract the hours' count from 12 if it is greater than 12 and another property session for displaying AM or PM.

FAQs

1. What is Date( )?

The javascript ‘Date()’ function is used for initialising a date object for performing operations on dates and working with dates and time/timezones in JS.   

2. How setInterval( ) function works?

The javascript ‘setInterval()’ function is a scheduling function that triggers some actions (schedules) to be automatically executed/called after a predefined duration of time. A sample working of the function can be demonstrated in the following manner:

setInterval(function(){

    // getting the time
    var time = getCurrentTime();
    // Replace the current text
    document.getElementById('time').innerText = time;
},1000);
You can also try this code with Online Javascript Compiler
Run Code

Above function executes the asynchronous function after an interval of every 1000ms.

Key Takeaways

This article covered how to implement a digital watch using vanilla js.

Check out the Coding Ninjas Studio library for getting a better hold of the data structures and algorithms and the guided path for learning javascript from basics.

Side by side, you can also practice a wide variety of coding questions commonly asked in interviews in Coding Ninjas Studio. Along with coding questions, you can also find the interview experience of scholars working in renowned product-based companies here. 

Happy learning!

Live masterclass