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:
-
How to Make Asynchronous Requests in a Loop in JavaScript
Implementing asynchronous requests inside a JavaScript loop may not seem obvious at first. When making asynchronous requests inside a JavaScript loop, it is important to ...
-
Iterating Elements of Array without Loops
The examples are very abstract because there are cycles. Our condition will be as follows. It is necessary to select all elements of the array by a given attribute. Or, t...
-
jQuery Accordion Plugin
An accordion is often used on websites. This element is popular and convenient at the same time. An accordion helps to structure content and save space. In my work, I oft...
You’ve written something that not only informs, but also inspires a sense of wonder and possibility.