Fixed issue with multiple ticks

This commit is contained in:
Arjun Mahishi
2018-12-27 15:47:53 +05:30
parent a8fc4ce581
commit 889ac4ff15

View File

@ -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>
);
}
}
```