Skip to content
Permalink
84a856c017
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
50 lines (41 sloc) 2.18 KB
//Counter variable for # of SECONDS (set to zero)
let count = 0;
//Global variable defined to store the interval when it is active:
let stopWatch = 0;
//Reference to the display paragraph in a variable
const displayPara = document.querySelector(".clock");
//Callback function to calculate current hours, minutes, and seconds, and display the count
function displayCount() { //(abbreviated to hrs, min, sec)
let hrs = Math.floor(count/3600); //3600 sec in 1 hr.
let min = Math.floor((count % 3600)/60); //remainder of seconds left over when all hrs are removed, DIVIDED by 60
let sec = Math.floor(count % 60); //remainder of seconds left over when all the min are removed
//Show a leading zero if the values are less than 10
let displayHrs = (hrs < 10) ? '0' + hrs : hrs;
let displayMin = (min < 10) ? '0' + min : min;
let displaySec = (sec < 10) ? '0' + sec : sec;
//Stopwatch display time written into the display paragraph varable
displayPara.textContent = displayHrs + ":" + displayMin + ":" + displaySec;
count++; //counter variable increments by one every second (constant loop)
}
//References to the button classes
const startBtn = document.querySelector(".start");
const stopBtn = document.querySelector(".stop");
const resetBtn = document.querySelector(".reset");
//Once the start btn is pressed, start running displayCount() once per second using setInterval()
startBtn.addEventListener("click", function() {
stopWatch = setInterval(displayCount, 1000);
startBtn.disabled = true; //start btn is UNCLICKABLE (diabled) upon clicking on it as it's already running!
});
//Once the stop btn is pressed, clear the interval
stopBtn.addEventListener("click", function() {
clearInterval(stopWatch);
startBtn.disabled = false; //start btn is CLICKABLE upon clicking the stop btn for the user to start count again!
});
//Once the reset btn is pressed, clear the interval AND the display (00:00:00)
resetBtn.addEventListener("click", function() {
clearInterval(stopWatch);
startBtn.disabled = false; //start btn is CLICKABLE upon clicking the reset btn for the user to start count again!
count = 0; //set counter back to zero
displayCount();
});
displayCount();