How to make a live clock with JavaScript?

Sometimes, we want to make a live clock with JavaScript.

In this article, we’ll look at how to make a live clock with JavaScript.

How to make a live clock with JavaScript?

To make a live clock with JavaScript, we can use the setInterval function.

For instance, we write:

<span></span>

to add a span.

Then we write:

const span = document.querySelector('span');

const time = () => {
  const d = new Date();
  const s = d.getSeconds().toString().padStart(2, '0');
  const m = d.getMinutes().toString().padStart(2, '0');
  const h = d.getHours().toString().padStart(2, '0');
  span.textContent = `${h}:${m}:${s}`
}

setInterval(time, 1000);

to select the span with querySelector.

Then we define the time function that populates the span with the time.

In it, we create a Date instance that returns the current date time.

Then we get get hours, minutes, and seconds with getHours, getMinutes, and getSeconds.

We convert them to strings with toString.

And we prepend a 0 to each string if their length is less than 2 with padStart.

Next, we set span.textContent to the time string to show the current time.

Finally, we call setInterval with time and 1000 to call time every second.

Conclusion

To make a live clock with JavaScript, we can use the setInterval function.