[JS] Digital Clock (24-hour) Template
How to display the current time in real-time using JavaScript
⏰ Use Cases and Benefits of This Template
- Can display the current time in real-time
- Learn the basics of
setInterval - Experience automatic updates without events
- Applicable for blogs, stores, and educational settings
📋 Copy and use the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Current Time Display</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
background-color: #f0f0f0;
}
#clock {
font-size: 3rem;
font-weight: bold;
color: #333;
}
</style>
</head>
<body>
<h1>Current Time</h1>
<div id="clock">--:--:--</div> <!-- Initial value is set to "--:--:--" -->
<script>
setInterval(() => {
const now = new Date();
const hh = now.getHours().toString().padStart(2, '0'); // Hours
const mm = now.getMinutes().toString().padStart(2, '0'); // Minutes
const ss = now.getSeconds().toString().padStart(2, '0'); // Seconds
document.getElementById("clock").textContent = `${hh}:${mm}:${ss}`; // Display time
}, 1000); // Update every 1 second
</script>
</body>
</html>
🧩 Applications and Usage Tips
This template uses setInterval(() => {...}, 1000) to update the current time every second. Since the time is displayed in real-time without needing to reload the page, it's perfect for situations like digital signage, information kiosks, or anywhere that requires up-to-date clock displays.
Additionally, the use of padStart(2, '0') ensures that single-digit numbers are always displayed with two digits, keeping the clock neatly formatted.
💡 Customization Ideas
If you'd like to add AM/PM indicators, you can use conditional logic based on the value of getHours(). To include the date or day of the week, you can use getFullYear() and getDay().
The clock's appearance can be easily customized with CSS, so feel free to change the background color or font size to better match your website's design.