Let's create a simple digital clock using JavaScript. We'll use HTML to create the structure and JavaScript to update the time dynamically.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Simple Digital Clock</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
#clock {
font-size: 48px;
}
</style>
</head>
<body>
<div id="clock"></div>
<script src="clock.js"></script>
</body>
</html>
JavaScript (clock.js):
javascript
function updateClock() {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
const timeString = `${hours}:${minutes}:${seconds}`;
document.getElementById('clock').textContent = timeString;
}
// Call updateClock() every second to update the time
setInterval(updateClock, 1000);
// Initial call to set the clock when the page loads
updateClock();
In this example, we have a simple HTML structure with a `<div>` element to display the clock. We also have some minimal CSS to center the clock on the screen and apply a larger font size.
The JavaScript code uses the `setInterval` function to call the `updateClock` function every second (1000 milliseconds). The `updateClock` function gets the current date and time using the `Date` object, formats the hours, minutes, and seconds with leading zeros, and then updates the content of the `<div>` element with the current time.
When you open this HTML file in your web browser, you should see a digital clock displaying the current time, and it will automatically update every second.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc