Update Ticker
This commit is contained in:
@ -2,45 +2,37 @@
|
||||
|
||||
Renders a ticker component.
|
||||
|
||||
- The ticker state is initially set to zero
|
||||
- When the `Tick!` button is clicked, `timer` is incremented periodically at the given `interval`
|
||||
- When the `Reset` button is clicked, the value of the timer is set to zero and the `setInterval` is cleared
|
||||
- The `setInterval` is cleared once the desired `time` is reached
|
||||
- `time` and `interval` are the required props
|
||||
Use the `React.useState()` hook to initialize the `ticker` state variable to `0`.
|
||||
Define two methods, `tick` and `reset`, that will periodically increment `timer` based on `interval` and reset `interval` respectively.
|
||||
Return a `<div>` with two `<button>` elements, each of which calls `tick` and `reset` respectively.
|
||||
|
||||
```jsx
|
||||
class Ticker extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {ticker: 0}
|
||||
this.interval = null
|
||||
}
|
||||
function Ticker(props) {
|
||||
const [ticker, setTicker] = React.useState(0);
|
||||
let interval = null;
|
||||
|
||||
tick = () => {
|
||||
this.reset()
|
||||
this.interval = setInterval(() => {
|
||||
if (this.state.ticker < this.props.times) {
|
||||
this.setState(({ ticker }) => ({ticker: ticker + 1}))
|
||||
}else{
|
||||
clearInterval(this.interval)
|
||||
}
|
||||
}, this.props.interval)
|
||||
}
|
||||
const tick = () => {
|
||||
reset();
|
||||
interval = setInterval(() => {
|
||||
if (ticker < props.times)
|
||||
setTicker(ticker + 1);
|
||||
else
|
||||
clearInterval(interval);
|
||||
}, props.interval);
|
||||
}
|
||||
|
||||
reset = () => {
|
||||
this.setState({ticker: 0})
|
||||
clearInterval(this.interval)
|
||||
}
|
||||
const reset = () => {
|
||||
setTicker(0);
|
||||
clearInterval(interval);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<span style={{fontSize: 100}}>{this.state.ticker}</span>
|
||||
<button onClick={this.tick}>Tick!</button>
|
||||
<button onClick={this.reset}>Reset</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<span style={{ fontSize: 100 }}>{this.state.ticker}</span>
|
||||
<button onClick={this.tick}>Tick!</button>
|
||||
<button onClick={this.reset}>Reset</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user