41 - Stopwatch app that tracks elapsed time
Description
Develop a React component that functions as a stopwatch, tracking elapsed time and providing start/stop controls.
Visually displays the elapsed time in a clear format (minutes, seconds, milliseconds).
Offers start, stop, and reset buttons.
Continues to count time even when the browser tab is inactive.
Optionally supports features like:
Lap times
Countdown timer mode
Sound alerts
Algorithm
Component Structure:
Define a functional component named
Stopwatch
.Maintain internal state for:
isRunning
: Boolean indicating if the stopwatch is active.elapsedTime
: Number storing the elapsed time in milliseconds.intervalId
: Reference to the interval timer for updates.Optionally:
lapTimes
: Array to store lap times.
Time Tracking:
Use
setInterval
to create an interval that updates theelapsedTime
state every millisecond when the stopwatch is running.Calculate and display the elapsed time in a readable format (minutes, seconds, milliseconds).
Start/Stop Buttons:
Implement
startStopwatch
andstopStopwatch
functions:startStopwatch
: SetsisRunning
to true, starts the interval timer, and stores the start time.stopStopwatch
: Clears the interval timer (clearInterval
), setsisRunning
to false, and optionally records a lap time.
Reset Button:
Implement a
resetStopwatch
function to clear theelapsedTime
state and stop the timer if running.
Code
Explanation
State Management:
useState
variables track running state, elapsed time, interval timer reference, and lap times.Time Tracking:
useEffect
hook manages the interval timer and updates the elapsed time every 10 milliseconds when running.Start/Stop/Reset Buttons: Functions update
isRunning
state and optionally record lap times.Formatting:
formatTime
function converts milliseconds to a readable format.Rendering: Displays the stopwatch display, buttons, and lap times dynamically based on state.
Additional Notes
This is a basic example and can be further customized with styling, animations, and sound effects.
Consider additional features like pause functionality, target time countdown, and data persistence beyond page refreshes.
Integrate the stopwatch into your website or application with appropriate UI elements and interactions.
Last updated