How To Make a Digital Clock Using Javascript
The clock updates automatically every second, providing an interactive and dynamic experience for the users.
Feel free to customize the styling or integrate the clock into your own web projects. Remember to experiment with the code and explore additional features you can add to enhance the clock's functionality .
Project Source Code:
<!DOCTYPE html>
<html>
<head>
<title>Digital Clock</title>
<style>
#clock{
display: block;
width: 40%;
margin: 10px auto;
padding: 10px;
background-color: #3c3c3c;
color: #fff;
font-size: 36px;
font-family: Arial, sans-serif;
text-align: center;
border-radius: 5px;
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.5);
}
</style>
</head>
<body>
<div id="clock"></div>
<script>
function updateClock()
{
// get the current time
var currentTime = new Date();
// get the hours, minutes, and seconds from the
// current time
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
// format the hours, minutes,
// and seconds to always display two digits
if(hours < 10) { hours = "0" + hours; }
if(minutes < 10) { minutes = "0" + minutes; }
if(seconds < 10) { seconds = "0" + seconds; }
// get the clock div
var clockDiv = document.getElementById("clock");
// update the clock div with the current time
clockDiv.innerHTML = hours + ":" + minutes + ":" + seconds;
}
// calls the updateClock() function every 1000 milliseconds
// (or 1 second)
setInterval(updateClock, 1000);
</script>
</body>
</html>
Code Explanation:
This JavaScript code consists of a function called updateClock(), which is responsible for fetching the current time, formatting it, and updating the clock display on the webpage. Let's break down the code to understand its functionality.
Fetching Current Time: The updateClock() function starts by creating a new Date object called currentTime, which holds the current date and time.
Extracting Hours, Minutes, and Seconds: Next, the code extracts the hours, minutes, and seconds from the currentTime object using the getHours(), getMinutes(), and getSeconds() methods, respectively.
Formatting Time: To ensure that the hours, minutes, and seconds are always displayed with two digits, the code checks if any of them are less than 10. If so, a leading zero is added to the value using simple conditional statements.
Updating the Clock Display: The code retrieves the clock element from the webpage using the getElementById() method and assigns it to the clockDiv variable. Then, it updates the innerHTML property of the clockDiv with the formatted time (hours, minutes, and seconds).
Automatic Clock Update: To make the clock update every second, the code employs the setInterval() function. It calls the updateClock() function every 1000 milliseconds (1 second), ensuring that the displayed time is always accurate and up to date.
OUTPUT:
Download Projects Source Code