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 trialJeff Lange
8,788 PointsWhy 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
231,141 PointsYou'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
8,788 PointsThanks Steven, I appreciate that