JavaScript - 25

JavaScript - 25: Digital Clock

Create a live digital clock that updates every second using setInterval(). Display hours, minutes, and seconds.

✦ JavaScript Editor
▶ Live Output

👀 Show Solution
const clock = document.getElementById("clock");

function updateClock() {
  const now = new Date();
  
  let hours = now.getHours();
  let minutes = now.getMinutes();
  let seconds = now.getSeconds();
  
  hours = hours < 10 ? "0" + hours : hours;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;
  
  clock.textContent = \`\${hours}:\${minutes}:\${seconds}\`;
}

setInterval(updateClock, 1000);
updateClock();