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 trialLaurence kite
11,768 PointsSetinterval
I am struggling to understand this React Code its basic JavaScript but seems tricky.
It implements a stop watch using setInterval which call onTick every 100 ms.
It appears to me that time between each call to onTick is 100ms but apparently its not quiet that accurate. So we call Date.now() to get a timestamp and store that in now we then set previous time to now to. I therefore feel that the variable now and previous time are storing the same timestamp? The next tick does the same so the previous time is never set to anything but now.
Here is the code:
componentDidMount: function() {
this.interval = setInterval(this.onTick, 100);
},
componentWillUnMount: function() {
clearInterval(this.interval);
},
onTick: function() {
if (this.state.running) {
var now = Date.now();
this.setState({
previousTime: now,
elapsedTime: this.state.elapsedTime + (now - this.state.previousTime),
});
}
console.log('onTick');
},
Does this var now = Date.now(); set now and then previousTime: now, at this point both variables are the same value?
elapsedTime: this.state.elapsedTime + (now - this.state.previousTime),
It seems that: (now - this.state.previousTime) = 0 ?
2 Answers
Steven Parker
231,269 PointsThe expression "now - this.state.previousTime" is being evaluated before "setState" is called, so it will not be 0 but the amount of time that has elapsed since the last time "setState" was called. So adding it to the previous elapsed time amount updates and makes the elapsed time current.
Computing the time offset this way makes the calculation independent of interval, not only in terms of accuracy but you could change the interval to increase or decrease the resolution as you wish.
Laurence kite
11,768 PointsI have worked out what you meant so thanks, I changed the order of the code so that its clearer to me and it still works
onTick: function() {
if (this.state.running) {
var now = Date.now();
this.setState({
elapsedTime: this.state.elapsedTime + (now - this.state.previousTime),
previousTime: now,
});
}
console.log('onTick');
},
previousTime at the bottom now, just seems better.