DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Markus Wedler
Markus Wedler

Posted on • Updated on

Stopwatch in React

The Website: Link

So I made a stopwatch in React.
The whole code is located down below.

Few Notes

❔How the time is calculated

Let's say we just started the stopwatch. We have the startTime, elapsedTime is counting the time now, time too, but time equals elapsedTime only at the beginning.
Now we click pause.
We don't care about startTime now. elapsedTime stops. time too. But stopTime now equals time.
We click play.
startTime is set. elapsedTime is counting from 0. time is counting from the value of stopTime. And time is the time we see on the screen.
Think variables' names are a bit confusing here. If u have some ideas how to rename them, please let me know.

❕A question for you

There's some trouble. In a row if(s == 0 && ms == 1){ in playTime() I wanted to type if(s == 0){. Has some logic, right? instead of calculating minutes at 00s 01ms function could just calculate it at 00s. But! After waiting 1min you'll have 1m00s00ms. If you click reset button it's gonna be 00s00ms. And if there's shorter version of condition, it'll show 1m00s00ms on a new play. I had hard time trying understand why it happens so, but still no clue.
Also it would be great if you have some others code improvements or so.

The Full Code

GitHub: Link

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post