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));
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.