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

Jeff Lange
Jeff Lange
8,788 Points

Why use elapsedTime, previousTime, and calculations instead of just storing seconds?

The video specifies doing the following:

componentDidMount() {
  this.intervalID = setInterval(() => this.tick(), 100);
}

tick = () => {  
  const now = Date.now();
  this.setState({
    previousTime: now,
    elapsedTime: this.state.elapsedTime + (now - this.state.previousTime)
  })
}

I accomplished the same thing by putting my setInterval function to 1000 (one second), and only specifying the value seconds in my state. So I update going:

componentDidMount() {
  this.intervalID = setInterval(() => this.tick(), 1000);
}

tick = () => {  
  this.setState( prevState => {
    return { seconds: prevState.seconds += 1 }
  });
}

What's the advantage of using previousTime and elapsedTime, plus the calculation? I assume it makes the stopwatch a little more accurate or something.

2 Answers

Steven Parker
Steven Parker
215,984 Points

You're exactly right, calculating the elapsed time gives you an accuracy based on milliseconds.

But in many applications, seconds are perfectly adequate; and as your example shows, simpler to implement.

Jeff Lange
Jeff Lange
8,788 Points

Thanks Steven, I appreciate that