The HTML contains a heading and a container where the current time will be displayed.
<div class="clock-container">
<h1>Digital Clock</h1>
<div id="clock">00:00:00</div>
</div>
-
<h1>displays the title. -
<div id="clock">initially shows 00:00:00. - JavaScript updates this element every second. Style the Clock with CSS We use Flexbox to center the clock on the page and give it a clean card design.
body{
height:100vh;
display:flex;
justify-content:center;
align-items:center;
background:#0f172a;
}
Display the Current Time
function showTime() {
let date = new Date();
let hours = String(date.getHours()).padStart(2,'0');
let minutes = String(date.getMinutes()).padStart(2,'0');
let seconds = String(date.getSeconds()).padStart(2,'0');
let time = `${hours}:${minutes}:${seconds}`;
document.getElementById("clock").innerHTML = time;
}
-
new Date()Creates a Date object containing the current date and time. - (Fri Jul 17 2026 14:35:42).
- getHours() Returns the current hour.
- getMinutes() Returns the current minutes.
- getSeconds() Returns the current seconds.
- padStart() Ensures every value contains two digits.
- Without padStart(): 5:7:9
- With padStart(): 05:07:09 Syntax
string.padStart(targetLength, padString)
padStart(2,'0')
2 Make the total length 2 characters.'0' If needed, add 0 on the left.
Template Literals
let time = `${hours}:${minutes}:${seconds}`;
Combines the values into a time string.
09:15:42
Update the HTML
document.getElementById("clock").innerHTML = time;
Updates the content of the <div id="clock"> element with the latest time.
Update Every Second
setInterval(showTime,1000);
setInterval() repeatedly executes a function.
Syntax:
setInterval(functionName,timeInMilliseconds);
Since 1000 milliseconds equals 1 second, the clock refreshes every second.
Show the Time Immediately
showTime();
Without this line, the page would display:
00:00:00
until the first second passes.Calling showTime() immediately displays the correct time as soon as the page loads.
Top comments (0)