Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Amandeep Pasricha
Amandeep Pasricha
14,932 Points

Can someone please explain the concept behind elapsedTime and previousTime?

I honestly still don't understand what we're doing with these two things. Why do we need a previous time in the first place? I've been on this for hours.

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()