Skip to content

Stopwatch Timer

Easy ~20 min

What you'll build

A stopwatch displaying elapsed time in MM:SS.ms format with Start, Stop, and Reset buttons. The timer updates every 10 milliseconds while running.

Goals

  • Use setInterval to update the timer
  • Track elapsed time with a timestamp
  • Format milliseconds into MM:SS.ms display
  • Start, stop, and reset the timer

Prerequisites

  • Variables and arithmetic
  • Functions and closures
  • DOM selection and event listeners

Steps

  1. 1

    Create the HTML

    Create a display div for the timer and three buttons: Start, Stop, Reset.

    Code
    <div id="display">00:00.0</div>
    <button id="start">Start</button>
    <button id="stop">Stop</button>
    <button id="reset">Reset</button>

    Expected result

    A timer display showing 00:00.0 and three buttons appear.

  2. 2

    Set up state and formatting

    Declare variables for elapsed time, interval ID, and running state. Write a format function that converts milliseconds to MM:SS.ms.

    Code
    let elapsed = 0;
    let intervalId = null;
    let running = false;
    
    function format(ms) {
      const totalSec = Math.floor(ms / 1000);
      const min = String(Math.floor(totalSec / 60)).padStart(2, "0");
      const sec = String(totalSec % 60).padStart(2, "0");
      const tenths = Math.floor((ms % 1000) / 100);
      return `${min}:${sec}.${tenths}`;
    }

    Expected result

    format(65430) returns '01:05.4'.

  3. 3

    Wire the buttons

    Start: record start time and use setInterval to update elapsed every 10ms. Stop: clear the interval. Reset: stop and set elapsed to 0.

    Code
    const display = document.getElementById("display");
    let startTime = 0;
    
    document.getElementById("start").addEventListener("click", () => {
      if (running) return;
      running = true;
      startTime = Date.now() - elapsed;
      intervalId = setInterval(() => {
        elapsed = Date.now() - startTime;
        display.textContent = format(elapsed);
      }, 10);
    });
    document.getElementById("stop").addEventListener("click", () => {
      running = false;
      clearInterval(intervalId);
    });
    document.getElementById("reset").addEventListener("click", () => {
      running = false;
      clearInterval(intervalId);
      elapsed = 0;
      display.textContent = format(0);
    });

    Expected result

    Start begins timing, Stop pauses, Reset returns to 00:00.0.

  4. 4

    Add input validation & error handling

    Add validation at user input points: check for empty values, non-numbers, negatives, and other anomalies, using try/catch or conditionals to show friendly messages. Robust JS programs don't crash on unexpected input.

    Code
    function safeParse(value) {
      if (value === null || value === undefined || value === "") {
        throw new Error("Input is empty");
      }
      const num = Number(value);
      if (Number.isNaN(num)) {
        throw new Error(`"${value}" is not a valid number`);
      }
      return num;
    }
    
    try {
      const n = safeParse(userInput);
      process(n);
    } catch (err) {
      console.error(err.message);
    }

    Expected result

    Empty or non-number input shows an error message instead of crashing; valid numbers process normally.

  5. 5

    Add event listeners & interaction

    Bind event listeners (click, input, keydown, etc.) to page elements so the program responds to user actions. Interactivity is the core value of JavaScript in the front end.

    Code
    const button = document.querySelector("#action-btn");
    const input = document.querySelector("#user-input");
    
    button.addEventListener("click", () => {
      const value = input.value.trim();
      if (!value) return;
      runMainLogic(value);
    });
    
    input.addEventListener("keydown", (e) => {
      if (e.key === "Enter") button.click();
    });

    Expected result

    Clicking the button or pressing Enter triggers the main logic; empty input is ignored.

Try it yourself

What you learned

You built a stopwatch using setInterval, Date.now() for accurate timing, and clearInterval for pausing — the fundamental pattern for any timer or polling application.

Related Resources

Related Lessons

  • Functions

    Closures and timer callbacks.

  • DOM

    Event listeners for button controls.

Related Practice

Related Cheatsheets

Related Glossary

Related Glossary

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic