Simple JavaScript Clock
There are many examples of implementing a clock using JavaScript, and while the approaches may vary slightly, most of them follow a similar idea. Typically, such functionality is built using timing functions like setTimeout or setInterval, which allow the interface to update the displayed time at regular intervals.
Even though the logic behind a simple clock is not very complex, it is a great practical exercise for understanding how the Date object works in JavaScript. By building a clock from scratch, you can learn how to retrieve the current time, format hours, minutes, and seconds, and update the UI dynamically without reloading the page.
In this example, we will create a simple digital clock in 24-hour format using the setTimeout function. This approach gives more control over the update cycle and can be slightly more flexible compared to setInterval. Along the way, we will also handle basic formatting tasks, such as adding leading zeros to single-digit values, so that the time is displayed in a clean and consistent format.
HTML
<div id="clock"></div>
JavaScript
function clock() {
const date = new Date();
let hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds();
if (hours < 10) hours = '0' + hours;
if (minutes < 10) minutes = '0' + minutes;
if (seconds < 10) seconds = '0' + seconds;
const time = hours + ':' + minutes + ':' + seconds;
document.getElementById('clock').innerText = time;
setTimeout(() => {
clock();
}, 1000);
}
clock();
You can see an example on Codepen: https://codepen.io/igorrybalko/pen/wBwzKeE
Similar posts:
-
Smooth Scrolling to Anchor Using JavaScript
Smooth scrolling is a popular web design feature that enhances user experience by allowing seamless navigation between sections of a webpage. Instead of abrupt jumps, smo...
-
How to Create a Custom jQuery Plugin
The convenience of the jQuery plugin is that you can use the same code several times for different objects. In this case, copy-paste code is not needed. In addition, you ...
-
Working with Cookies in JavaScript
Сookie (web cookie or browser cookie) is a string of information that can be stored in a browser and sent to the server. The maximum size for one cookie is 4096 bytes. T...
You’ve written something that not only informs, but also inspires a sense of wonder and possibility.