Update Ticker

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-09-06 14:46:23 +03:00
parent 75a640a1ab
commit 3b074c301c

View File

@ -6,25 +6,25 @@ tags: components,state,beginner
Renders a ticker component. Renders a ticker component.
- Use the `React.useState()` hook to initialize the `ticker` state variable to `0`. - 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. - Define two methods, `tick` and `reset`, that will periodically increment `timer` based on `intervalId` and reset `intervalId` respectively.
- Return a `<div>` with two `<button>` elements, each of which calls `tick` and `reset` respectively. - Return a `<div>` with two `<button>` elements, each of which calls `tick` and `reset` respectively.
```jsx ```jsx
function Ticker(props) { const Ticker = ({ times, interval }) => {
const [ticker, setTicker] = React.useState(0); const [ticker, setTicker] = React.useState(0);
let interval = null; let intervalId = null;
const tick = () => { const tick = () => {
reset(); reset();
interval = setInterval(() => { intervalId = setInterval(() => {
if (ticker < props.times) setTicker(ticker + 1); if (ticker < times) setTicker(ticker + 1);
else clearInterval(interval); else clearInterval(intervalId);
}, props.interval); }, interval);
}; };
const reset = () => { const reset = () => {
setTicker(0); setTicker(0);
clearInterval(interval); clearInterval(intervalId);
}; };
return ( return (
@ -34,7 +34,7 @@ function Ticker(props) {
<button onClick={reset}>Reset</button> <button onClick={reset}>Reset</button>
</div> </div>
); );
} };
``` ```
```jsx ```jsx