JSFiddle - React, Tailwind, and code Playground

by Michel Plungjan

HTML

<div class="container">
  <div id="timer">00:00</div>
  <button type="button" id="start">Start</button>
</div>

CSS

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  flex-direction: column;
  background: #e9c46a;
}

#timer {
  margin-bottom: 25px;
  font-size: 3rem;
  font-weight: bold;
  color: #2a9d8f;
}

#timer.odd {
  color: #264653;
}

button {
  border-radius: 5px;
  display: inline-block;
  border: none;
  padding: 1rem 2rem;
  margin: 0;
  text-decoration: none;
  background: #e76f51;
  color: #fff;
  font-family: sans-serif;
  font-size: 1rem;
  cursor: pointer;
  text-align: center;
  transition: background 250ms ease-in-out;
  -webkit-appearance: none;
  -moz-appearance: none;
}

button:hover {
  background: #f4a261;
}

JavaScript

const pad = num => num.toString().padStart(2, "0");
let timerInterval;
const startTimer = () => {
  // First we start by clearing the existing timer, in case of a restart
  clearInterval(timerInterval);
  // Then we clear the variables
  let second = 0,
    minute = 0,
    hour = 0,
    odd = false;

  // Next we set a interval every 1000 ms
  timerInterval = setInterval(function() {
    // check if we are odd or even and append class to timer
    odd = !odd;
    timer.classList.toggle('odd',odd);
    // We set the timer text to include a two digit representation
    const arr = [hour, pad(minute), pad(second)]
    if (!hour) arr.splice(0, 1)
    timer.innerHTML = arr.join(":")
    // Next, we add a new second since one second is passed
    second++;
    // We check if the second equals 60 "one minute"
    if (second == 60) {
      // If so, we add a minute and reset our seconds to 0
      minute++;
      second = 0;
    }
    // If we hit 60 minutes "one hour" we reset the minutes and plus an hour
    if (minute == 60) {
      hour++;
      minute = 0;
    }
  }, 1000);
};
window.addEventListener("DOMContentLoaded", () => document.getElementById("start").addEventListener("click", startTimer));