Stopwatch & Countdown Timer: how it works and how to build one
Stopwatch with laps and a countdown timer with alarm. This guide explains what happens behind the button and shows the code, so you can build your own.
What it does
A stopwatch with lap times and a countdown timer with a sound when it ends. Quick buttons for 1, 5, 10 and 25 minutes (a Pomodoro). Keeps running if you switch tabs.
When to use it
- Workouts and cooking
- Pomodoro focus sessions
- Timing talks and exams
How to use it
- Pick stopwatch or timer.
- Start, pause, lap or reset.
- For the timer, set the time and wait for the beep.
Try it free in your browser, nothing is uploaded: https://eskillsfy.com/tools/stopwatch-timer
How it works
A reliable stopwatch never counts ticks; it stores the start time and shows now − start. Background tabs slow timers down, but Date.now() is always right, so the display is correct when you come back.
The countdown stores the end time and plays a beep with the Web Audio API (an oscillator) when the remaining time reaches zero.
Build it yourself
Here is the core of the tool. It has no dependencies unless noted, so you can paste it into any TypeScript or JavaScript project.
stopwatch.ts (ts)
export function createStopwatch() {
let start = 0, acc = 0, running = false;
return {
start() { if (!running) { start = Date.now(); running = true; } },
pause() { if (running) { acc += Date.now() - start; running = false; } },
reset() { acc = 0; running = false; },
elapsed: () => acc + (running ? Date.now() - start : 0),
};
}
export function beep() {
const ctx = new AudioContext(), osc = ctx.createOscillator();
osc.frequency.value = 880; osc.connect(ctx.destination);
osc.start(); osc.stop(ctx.currentTime + 0.3);
}
Make it production-ready
- Show the remaining time in the tab title.
- Use a Notification when the timer ends.
Questions
Does it work in the background?
Yes. It uses real clock time, so it stays correct even if the tab is in the background.
Free, runs in your browser, nothing is uploaded.