Build a JavaScript Stopwatch
In this project, you will learn how to build a digital stopwatch using JavaScript. You will learn how to start, stop and reset a timer while updating the display in real time.
Project Introduction
A stopwatch measures elapsed time. It starts counting when the user presses Start and stops when the user presses Stop.
What You Will Learn
- JavaScript variables
- setInterval()
- clearInterval()
- Functions
- DOM manipulation
- Time formatting
- Event handling
Create the HTML Structure
First, create the stopwatch container and control buttons.
<div class="stopwatch">
<div id="display">
00:00:00
</div>
<button onclick="startTimer()">
Start
</button>
<button onclick="stopTimer()">
Stop
</button>
<button onclick="resetTimer()">
Reset
</button>
</div>
Create the Stopwatch Display
The display is the element where the current elapsed time will be shown.
<div id="display">
00:00:00
</div>
JavaScript can access this element using:
const display =
document.getElementById("display");
Create JavaScript Variables
We need variables to store the elapsed time and the interval ID.
let seconds = 0; let timer = null;
Why timer?
The timer variable will store the value returned by setInterval(). This allows us to stop the interval later.
Understand the Timer Logic
JavaScript provides setInterval() for repeatedly executing a function after a fixed amount of time.
timer = setInterval(function(){
seconds++;
}, 1000);
The value 1000 represents 1000 milliseconds, which equals one second.
Create the Start Function
The Start button should begin the timer.
function startTimer(){
if(timer !== null){
return;
}
timer = setInterval(function(){
seconds++;
updateDisplay();
}, 1000);
}
Create the Stop Function
The Stop button should pause the stopwatch.
function stopTimer(){
clearInterval(timer);
timer = null;
}
clearInterval() stops the interval created by setInterval().
Create the Reset Function
Reset should stop the timer and return the elapsed time to zero.
function resetTimer(){
stopTimer();
seconds = 0;
updateDisplay();
}
Format the Time
Raw seconds are not very easy to read. We can convert seconds into hours, minutes and seconds.
const hours =
Math.floor(seconds / 3600);
const minutes =
Math.floor((seconds % 3600) / 60);
const secs =
seconds % 60;
Add Leading Zero
function format(value){
return String(value)
.padStart(2, "0");
}
Update the Display
display.textContent =
format(hours) + ":" +
format(minutes) + ":" +
format(secs);
Add a Lap System
A lap feature allows the user to record the current stopwatch time without stopping the timer.
Create a Lap Array
let laps = [];
Add Current Time
function addLap(){
laps.push(seconds);
}
Complete Project Flow
Complete Stopwatch Project
You have now learned the main concepts required to build a JavaScript Stopwatch using timers and DOM manipulation.
Tutorial Completed! ⏱️
Now open the complete working Stopwatch project and test everything you have learned.
Run Complete Project Learn setTimeout()