🕒 Build a Digital Clock That Updates Every Second Using JavaScript
A digital clock is a great beginner JavaScript project to understand time, DOM manipulation, and real-time updates. In this tutorial, you’ll learn how to create a simple yet powerful digital clock that updates every second using HTML, CSS, and JavaScript.
✅ What You’ll Learn:
-
How to get the current time using JavaScript
-
How to display time on a webpage using HTML
-
How to style it with CSS
-
How to update the time every second using
setInterval()
🛠️ Step-by-Step Guide to Build a Digital Clock
🧩 Step 1: Set Up Your HTML File
This is the structure where our clock will appear.
🔍 Explanation:
-
<!DOCTYPE html>
: Declares this as an HTML5 document. -
<div class="clock-container">
: A container to hold our clock. -
<h1 id="clock">
: We’ll update this element with JavaScript to show the time. -
<script src="script.js">
: Loads our JavaScript code.
🎨 Step 2: Add Some CSS to Make It Look Good
Create a file named style.css
in the same folder and add this:
🔍 Explanation:
-
We center the clock both vertically and horizontally using Flexbox.
-
The clock text is styled to be large and easily readable.
💻 Step 3: Write JavaScript to Display and Update the Time
Create a file called script.js
and add the following code:
🔍 Explanation:
-
new Date()
: Gives us the current date and time. -
getHours()
,getMinutes()
,getSeconds()
: Extract time components. -
padStart(2, '0')
: Ensures the numbers are two digits. -
document.getElementById('clock')
: Selects the HTML element to display time. -
setInterval(updateClock, 1000)
: RepeatsupdateClock()
every second.
🎯 Final Output
When you open your HTML file in a browser, you’ll see a live digital clock that updates every second automatically — just like a real one!