Build an Accurate Stopwatch Timer in React: Step-by-Step Guide
Explore techniques for implementing a precise stopwatch timer and avoiding common pitfalls. This guide details building reliable timers for any application.
Table of contents
Creating a stopwatch timer may seem straightforward, but many developers often implement timers inaccurately, leading to time loss.
A common approach is to increment the time by one second or millisecond as needed, which might appear correct on paper. However, when compared with a precise stopwatch timer, this method tends to count slower over time.
In this article, I will show you a method to implement a stopwatch timer without losing time accuracy.
First, create a new file for the stopwatch component, and prepare the layout:
Next, we need to calculate the time correctly. Instead of doing increments, we should calculate the time difference between the start time and the current time.
Create a time
state to store the time difference, and isRunning
state to mark if the timer is active.
Complete the functions for start
, stop
, and reset
:
1. start
: store the start time and toggle the active state (isRunning
).
2. stop
: set isRunning
to inactive.
3. reset
: stop the timer and set the time to 0.
Now that everything is set, we can add the main function. Since we start the timer by setting isRunning
to true, we can monitor it with useEffect
. When isRunning
is true, we can use setInterval()
to calculate the time difference between current time and start time, Date.now() - startTimeRef.current)
in this instance.
For better visuals, the interval is set to 1 millisecond, meaning the timer will update every millisecond. Feel free to set the interval to any duration you like, the stopwatch time would still be accurate. :D