Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Components (2018) Stateful Components and Lifecycle Methods Update the Stopwatch State with componentDidMount()

Can someone please explain the concept behind elapsedTime and previousTime?

.

1 Answer

Say your current time is 12:00, then in 1 minute, your current time is 12:01. When it is 12:01 you can get the elapsed time by subtracting 12:00 from 12:01 which would be 1 minute. You then add that 1 minute to the elapsed time variable which starts at zero. At 12:02 you would subtract 12:01 (Which would be the previous time) to get another minute of elapsed time which you should then add to the elapsed time variable. At this point, you will have 2 minutes in the elapsed time variable.

We need to do things this way because the setInterval is not precise but you can get a precise time with Date.now()