Answer the question
In order to leave comments, you need to log in
How to use setInterval for a simple timer?
Good day. I'm starting to learn js, and immediately a pitfall - I can't use setInterval correctly. For example, when I click on a button, I want to start a simple timer that counts seconds:
function App() {
const[sec,setSec] =useState(0);
const MyTimer =()=>setInterval(()=>{setSec(sec+1)},1000);
return (
<div>
<button onClick={MyTimer}>start</button>
<h1>{sec}</h1>
</div>
);
}
export default App;
Answer the question
In order to leave comments, you need to log in
It's all about closure. The function passed to setInterval wraps the seconds variable with a value of zero. The interval works, but the second time the function is called, the seconds variable has the same value.
In setSeconds, you need to pass a function that will be called with the current value of seconds.
Like this:
function App() {
const [ seconds, setSeconds ] = React.useState(0)
// старый вариант, не работает
const startTimer = () => {
setInterval(() => {
setSeconds(seconds + 1)
}, 1000)
}
// новый вариант, работает
const startTimer = () => {
setInterval(() => {
setSeconds((seconds) => {
return seconds + 1
})
}, 1000)
}
return (
<div>
<button onClick={startTimer}>start</button>
<h1>{seconds}</h1>
</div>
)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question