K
K
Kentavr162021-05-02 11:25:14
React
Kentavr16, 2021-05-02 11:25:14

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;


when you press the button, the interval works 1 time. when you press it again, the numbers jump at all. It turned out to make the same timer using setTimeout, but I want to understand how it works. Rummaged through all the branches - I did not find a simple and correct explanation. Help with code please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tehfreak, 2021-05-04
@Kentavr16

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 question

Ask a Question

731 491 924 answers to any question