Stopwatch Timer
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
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
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.
Codelet 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
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.
Codeconst 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
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.
Codefunction 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
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.
Codeconst 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
<div id="display">00:00.0</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
<script>
// TODO: state, format, wire buttons
</script><div id="display">00:00.0</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
<script>
let elapsed = 0;
let intervalId = null;
let running = false;
let startTime = 0;
const display = document.getElementById("display");
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}`;
}
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);
});
</script>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 Practice
- Predict the Function Call Result
Practice function behavior.
Related Cheatsheets
- JavaScript Cheatsheet
Timer and DOM reference.
Related Glossary
- Function
Callbacks for timers.
- Event Listener
Button click handling.
Related Glossary
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
- Function
Callbacks for timers.
- Event Listener
Button click handling.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.