Creating a Real-Time Clock with JavaScript
O
Ohidur Rahman Bappy
MAR 22, 2025
How to Create a Real-Time Clock with JavaScript
Follow the code below to build a functional clock using JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Clock</title>
<script>
window.onload = function() { getTime(); } // Initialize the clock on window load
function getTime() {
// Get Current Date and Time
var today = new Date();
var h = today.getHours(); // Get Current Hours
var m = today.getMinutes(); // Get Current Minutes
var s = today.getSeconds(); // Get Current Seconds
// Format minutes and seconds
m = checkTime(m);
s = checkTime(s);
// Display the time in the specified element
document.getElementById('showClock').innerHTML = h + ':' + m + ':' + s;
// Update the time every second
setInterval(getTime, 1000);
}
// Add leading zero to numbers less than 10
function checkTime(i) {
return i < 10 ? '0' + i : i;
}
</script>
</head>
<body>
<!-- Display the current time -->
<h1>Current Time: <span id="showClock"></span></h1>
</body>
</html>
By incorporating this script into your webpage, you create a live-updating clock, enhancing the interactivity and functionality of your site.