JavaScript

Simple JavaScript Clock

Last updated: 21.02.2026
Views: 138

There are many examples of clock implementation using JavaScript on the Internet. The implementation options may be different, but they are usually similar. To create a clock, the setTimeout or setInterval function is used. Although the code is not complicated, it will be useful as practice in working with the Date object. We will make a simple clock in 24-hour format using the setTimeout function

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

author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

  • Countdown Timer in JavaScript
    Often on sites that sell something, you can find a countdown timer to a certain date. Such a script is usually needed for landing pages or online stores. In one of the pr...
  • 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 ...
  • 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 ...

One response to “Simple JavaScript Clock”

  1. xmc.pl says:

    You’ve written something that not only informs, but also inspires a sense of wonder and possibility.

Leave a Reply

Your email address will not be published. Required fields are marked *