Fixed issue with multiple ticks
This commit is contained in:
@ -5,7 +5,7 @@ Renders a timer component.
|
||||
The timer state is initially set to zero. When the `Tick!` button is clicked, `timer` is incremented periodically at the given `interval`. The `setInterval` is cleared once the desired `time` is reached. `time` and `interval` are the required props.
|
||||
|
||||
```jsx
|
||||
class Timer extends Component {
|
||||
class App extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {timer: 0}
|
||||
@ -13,6 +13,7 @@ class Timer extends Component {
|
||||
}
|
||||
|
||||
tick = () => {
|
||||
this.reset()
|
||||
this.interval = setInterval(() => {
|
||||
if (this.state.timer < this.props.time) {
|
||||
this.setState({timer: this.state.timer + 1})
|
||||
@ -22,19 +23,20 @@ class Timer extends Component {
|
||||
}, this.props.interval)
|
||||
}
|
||||
|
||||
reset = () => {
|
||||
this.setState({timer: 0})
|
||||
clearInterval(this.interval)
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<span style={{fontSize: 100}}>{this.state.timer}</span>
|
||||
<button onClick={this.tick}>Tick!</button>
|
||||
<button onClick={() => {
|
||||
this.setState({timer: 0})
|
||||
clearInterval(this.interval)
|
||||
}}>Reset</button>
|
||||
<button onClick={this.reset}>Reset</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user