A stopwatch is a perfect beginner project because it is small, visual, and teaches you the two things every interactive app needs: time and state. Start, stop, reset, and lap — four buttons, one timer, and a lot of learning.
How does it work? You keep track of when the timer started and how much time has already passed. Every 10 milliseconds, you work out the total elapsed time and update the display. Laps are just snapshots of that elapsed time, saved in a list.
<h2>Stopwatch</h2>
<p id="display">00:00:00</p>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
<button id="lap">Lap</button>
<ul id="laps"></ul>
let startTime = 0;
let elapsed = 0;
let timer = null;
function format(ms) {
const totalSeconds = Math.floor(ms / 1000);
const minutes = String(Math.floor(totalSeconds / 60)).padStart(2, '0');
const seconds = String(totalSeconds % 60).padStart(2, '0');
const centiseconds = String(Math.floor((ms % 1000) / 10)).padStart(2, '0');
return `${minutes}:${seconds}:${centiseconds}`;
}
function tick() {
const now = Date.now();
document.getElementById('display').textContent = format(elapsed + (now - startTime));
}
document.getElementById('start').addEventListener('click', () => {
if (timer) return; // already running
startTime = Date.now();
timer = setInterval(tick, 10);
});
document.getElementById('stop').addEventListener('click', () => {
if (!timer) return;
clearInterval(timer);
timer = null;
elapsed += Date.now() - startTime;
});
document.getElementById('reset').addEventListener('click', () => {
clearInterval(timer);
timer = null;
elapsed = 0;
document.getElementById('display').textContent = '00:00:00';
document.getElementById('laps').innerHTML = '';
});
document.getElementById('lap').addEventListener('click', () => {
if (!timer) return;
const li = document.createElement('li');
li.textContent = format(elapsed + (Date.now() - startTime));
document.getElementById('laps').appendChild(li);
});
This app is great for beginners because it teaches you setInterval, Date.now(), and state management in its simplest form. The key insight is that you never count ticks — you always compute the time from the clock, so the stopwatch stays accurate even if the browser slows down.
When should you build it? Whenever you want a project you can finish in one sitting and actually use — timing a workout, a study session, or a cooking step. You can extend it later with a countdown mode, or by saving the best lap.
The limits are worth knowing. setInterval is not perfectly precise, so a stopwatch is fine for everyday timing but not for anything that needs millisecond accuracy. And if the tab goes to sleep, the display pauses — the elapsed time is still correct when you come back, because it comes from the clock.
Start today: build the stopwatch above, time yourself reading one page of a book, and press Lap twice to see how the lap list works. The moment the display keeps ticking, you have built a real tool.
Top comments (0)