A digital clock in JavaScript can be created using the setInterval() function and the Date object. The setInterval() function is used to execute a function repeatedly at a specified time interval, and the Date object is used to get the current date and time.

Here is an example of how to create a basic digital clock in JavaScript:

function displayTime() {
  var date = new Date();
  var time = date.toLocaleTimeString();
  document.getElementById("clock").innerHTML = time;
}
setInterval(displayTime, 1000);

In the above example the function displayTime is invoked every second (1000ms) using setInterval function. This function get the current time using the new Date() object and the toLocaleTimeString() method, and update the element with the ID “clock” to show the current time.

You also can use template literals to format the time as you prefer

function displayTime() {
    var date = new Date();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
  
    document.getElementById("clock").innerHTML = `${hours < 10 ? '0' : ''}${hours}:${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  }
  
  setInterval(displayTime, 1000);

This is just a basic example and you can customize it to suit your needs, for example, by styling the clock using CSS, or by adding the date to the clock display.

Also Read:

Categorized in: