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.
|
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
|
```jsx
|
||||||
class Timer extends Component {
|
class App extends Component {
|
||||||
constructor(props) {
|
constructor(props) {
|
||||||
super(props);
|
super(props);
|
||||||
this.state = {timer: 0}
|
this.state = {timer: 0}
|
||||||
@ -13,6 +13,7 @@ class Timer extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
tick = () => {
|
tick = () => {
|
||||||
|
this.reset()
|
||||||
this.interval = setInterval(() => {
|
this.interval = setInterval(() => {
|
||||||
if (this.state.timer < this.props.time) {
|
if (this.state.timer < this.props.time) {
|
||||||
this.setState({timer: this.state.timer + 1})
|
this.setState({timer: this.state.timer + 1})
|
||||||
@ -22,19 +23,20 @@ class Timer extends Component {
|
|||||||
}, this.props.interval)
|
}, this.props.interval)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
reset = () => {
|
||||||
|
this.setState({timer: 0})
|
||||||
|
clearInterval(this.interval)
|
||||||
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<span style={{fontSize: 100}}>{this.state.timer}</span>
|
<span style={{fontSize: 100}}>{this.state.timer}</span>
|
||||||
<button onClick={this.tick}>Tick!</button>
|
<button onClick={this.tick}>Tick!</button>
|
||||||
<button onClick={() => {
|
<button onClick={this.reset}>Reset</button>
|
||||||
this.setState({timer: 0})
|
|
||||||
clearInterval(this.interval)
|
|
||||||
}}>Reset</button>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user