How to create a clock using JavaScript?

December 11, 2020#javascript

In the beginning, create a new HTML, CSS & JavaScript file..

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Clock using JavaScript</title>
    <link rel="stylesheet" href="style.css" />
    <script src="app.js" defer></script>
  </head>
  <body></body>
</html>

Then, put a h2 with three span with the ID hours, minutes and seconds..

<h2>
  <span id="hours">00</span> : <span id="minutes">00</span> :
  <span id="seconds">00</span>
</h2>

Now, it will look like this..

Add some basic styling with a background..

body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;

  min-height: 100vh;

  background-image: url("https://images.unsplash.com/photo-1605364441002-c1dbf7d9c7f1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&q=100");
  background-repeat: no-repeat;
  background-position: center 40%;

  display: flex;
  align-items: center;
  justify-content: center;
}

h2 {
  font-size: 7rem;
  color: white;
}

It will look like this..

After that, create the main function which will get the time and put it into the spans

// Define the hours, minutes & seconds elements.
const hoursEl = document.getElementById("hours");
const minutesEl = document.getElementById("minutes");
const secondsEl = document.getElementById("seconds");

function main() {
  const totalSeconds = new Date().getTime() / 1000;

  const hours = Math.floor(totalSeconds / 3600) % 24;
  const minutes = Math.floor(totalSeconds / 60) % 60;
  const seconds = Math.floor(totalSeconds) % 60;

  hoursEl.innerText = formatTime(hours);
  minutesEl.innerText = formatTime(minutes);
  secondsEl.innerText = formatTime(seconds);
}

// Format the time by adding 0 before the time if it's less than 10..
function formatTime(time) {
  return time < 10 ? `0${time}` : time;
}

// Initial call.
main();

// Call the function every second.
setInterval(main, 1000);

and yeah, now it's working..