The component has a state that tracks various properties of the stopwatch:
hours: The number of hours in the stopwatch.
minutes: The number of minutes in the stopwatch.
seconds: The number of seconds in the stopwatch.
milliseconds: The number of milliseconds in the stopwatch.
isRunning: A boolean indicating whether the stopwatch is currently running.
Constructor:
In the constructor, the initial state is set, with all time-related properties initialized to 0, and the flags for running and paused set to false.
constructor(props) {
super(props);
this.state = {
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0,
isRunning: false,
isPaused: false,
};
}
handleStartStop:
The handleStartStop method is responsible for toggling the start and stop functionality of the stopwatch. When the user clicks the "Start" button, it sets up a timer using setInterval to increment the time every 0.1 seconds. The time is calculated in seconds, and the state is updated accordingly.
The handlePause method is responsible for pausing the stopwatch. It sets the isRunning flag to false and the isPaused flag to true. It also clears the interval timer.
handlePause = () => {
this.setState({
isRunning: false,
isPaused: true,
});
clearInterval(this.timer);
};
handleReset:
The handleReset method resets all time-related properties to 0 and stops the timer by clearing the interval.
handleReset = () => {
this.setState({
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0,
isRunning: false,
isPaused: false,
});
clearInterval(this.timer);
};
componentWillUnmount:
The componentWillUnmount lifecycle method is used to clear the interval when the component is about to be unmounted to prevent memory leaks.
componentWillUnmount() {
clearInterval(this.timer);
}
render:
The render method displays the current time and buttons for starting, pausing, and resetting the stopwatch.
No comments:
Post a Comment