As @Luiz Felipe said in the comment, you are running the clearInterval
in its function, and not in the range itself. This is one of the points that needs to be corrected and we can do this with the hook useRef
.
Another point that needs to be corrected is that as this code is asynchronous, we should take extra care with the useState
and make a small adaptation to get the correct value of count
. You can read more about it in that reply.
Then the code will look like this:
function App() {
const [count, setCount] = React.useState(0);
const timerRef = React.useRef();
function showTimer() {
setCount(oldCount => (oldCount + 1));
}
function startTimer() {
timerRef.current = setInterval(showTimer, 1000);
}
function pauseTimer() {
clearInterval(timerRef.current);
}
return (
<div>
<p>{count}</p>
<button onClick={startTimer}>start</button>
<button onClick={pauseTimer}>pause</button>
</div>
)
}
ReactDOM.render(<App />, document.querySelector('#app'));
<div id="app"></div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
Another way to create this counter is by using the useEffect
, but still using the useState
and useRef
. You can read this article from Medium to see how it would look.
When you call
setInterval
, he returns an ID that identifies the intermission created. It is this ID that you need to pass to the functionclearInterval
. Currently, you are passing a function that has nothing to do with whatclearInterval
wait. You can use a reference (hookuseRef
) to keep and update this ID within your component.– Luiz Felipe