V
V
Viktor2020-03-02 16:42:58
React
Viktor, 2020-03-02 16:42:58

Why does setInterval work only once?

const [timer, setTimer] = useState(60);

    const startTime = () => {
       setInterval(() => {
           const newTime = timer - 1;
           setTimer(newTime);
           console.log(111)
       }, 1000);
    };


Why is the console shown every second, but setTimer only works once?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-03-02
@polyak-888


in the interval callback, timer will close on its original value of 60
for such cases, setTimer can take not only a new value, but also a function that will contain the current value of the timer, and which will return a new value
setTimer(currentTimer => currentTimer - 1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question