In my React app, I'm using setInterval()
to create a stopwatch effect. It's important to note that this can be a long running clock -- it could be on for 3-4 hours provided that the user is still on the "page" which is a strong possibility because it's a business app. In one module, I actually have two of them that may run simultaneously.
When the user clicks to start the clock, I simply commit the current date/time into my redux store and every second I go into the tick()
function to calculate the time difference and save it in my store in a pretty format that makes it look like a stop watch i.e. 01:03:07
It's working fine except, sometimes it doesn't respond to my click to stop
the clock immediately. There's a small delay after I click the button. I really can't put my finger on it yet because sometimes even after running for a long time, it works fine but I sometimes think the longer this runs the more side effects it may have. Maybe I'm wrong but that's why I'm asking this question.
Could there be memory penalties or other negative effects due to using setInterval()
if my clock is running for a long time?
Here's my approach:
class MyComponent extends Component {
constructor(props) {
super(props);
this.tick = this.tick.bind(this);
}
state = {
elapsedTime: ""
};
componentDidMount() {
this.interval = setInterval(this.tick, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
tick() {
// Calculate elapsed time using function I created.
const elapsedTime = getElapsedTime(startTime);
this.setState({ elapsedTime: elapsedTime });
}
render () {
return(
<div>{this.state.elapsedTime}</div>
);
}
}