.oooooo.     ooooooooo.    ooooo  oooooooooooo  oooooooooooo  ooooo  ooooo      ooo
 d8P'  `Y8b    `888   `Y88.  `888'  `888'     `8  `888'     `8  `888'  `888b.     `8'
888             888   .d88'   888    888           888           888    8 `88b.    8 
888             888ooo88P'    888    888oooo8      888oooo8      888    8   `88b.  8 
888     ooooo   888`88b.      888    888    "      888    "      888    8     `88b.8 
`88.    .88'    888  `88b.    888    888           888           888    8       `888 
 `Y8bood8P'    o888o  o888o  o888o  o888o         o888o         o888o  o8o        `8 
 

Stopwatch

Completed: 16 November 2025

As opposed to my first project, this one was a bit trickier than I first anticipated. I needed many more variables for this project. Perhaps there is a clock function in JavaScript, but I treated each set of two digits in the stopwatch as a separate numbers which are unified into a single string that replaces the display every 10 milliseconds. I don't know why it surprises me how fast code can run, but it's pretty cool to see the code you write execute faster than your eyes can even track.

Other things I learned how to do:

  • Add a click event listener on a button in the script, instead of an onclick attribute in the html element
  • Set a minimum string length and add a placeholder with padStart()
  • Set and clear an interval that runs a function at the given interval

Outcome:

00:00:00

Relevant Code:

const startStopButton = document.getElementById("startStop");
const resetButton = document.getElementById("reset");
const stopWatch = document.getElementById("stopwatch");

let interval = null;
let isRunning = false;
let minutes = 0, seconds = 0, cents = 0;

const formatTime = (num) => num.toString().padStart(2, "0");

function updateDisplay() {
    stopWatch.textContent = `${formatTime(minutes)}:${formatTime(seconds)}:${formatTime(cents)}`;
}

function updateCount() {
    cents++;
    if (cents === 100) {
    seconds++;
    cents = 0;
    }
    if (seconds === 60) {
    minutes++;
    seconds = 0;
    }
    updateDisplay();
}

startStopButton.addEventListener("click", () => {
    if (!isRunning) {
        interval = setInterval(updateCount, 10);
        startStopButton.textContent = "Stop";
    } else {
        clearInterval(interval);
        startStopButton.textContent = "Start";
    }
    isRunning = !isRunning;
});

resetButton.addEventListener("click", () => {
    clearInterval(interval);
    startStopButton.textContent = "Start";
    minutes = seconds = cents = 0;
    isRunning = false;
    updateDisplay();
})

Ways to Improve:

  • Add a lap/split function to the stopwatch
  • Saving your lap data to an external file
  • Mapping the spacebar to the startStop button
  • Make a countdown feature with an alarm when it reaches zero

Return to Projects