0

I am having trouble with setInterval. When I run the following code, setMilliseconds(milliseconds - 100); seems only to run once. Say milliseconds starts at 100, the console log just shows `900' in an infinite loop.

timer = setInterval(() => {
  setMilliseconds(milliseconds - 100);
  console.log(milliseconds);

  if (milliseconds <= 0) {
    console.log("stopped");
    clearInterval(timer);
    pause();
  }
}, 100);

setMilliseconds id defined above the code as const [milliseconds, setMilliseconds] = useState(0);

I almost never use setIterval. I a doing somithing wrong?

Here is the full file: https://gist.github.com/timscodebase/86fd0951a30b150b438a04a3fd5ec4c1

Tithos
  • 1,191
  • 4
  • 17
  • 40
  • There are subtleties to using `setInterval` with the `useState` hook. The answers to the question linked above go over those and provide alternatives and guidance. – Heretic Monkey May 02 '21 at 17:39
  • This is why so many devs hate Stackoverflow!!! – Tithos May 02 '21 at 18:17
  • ...Because they get pointed to answers to their questions? Because it is as simple as [edit]ing their question to explain *why* a duplicate question does not answer their question, as mentioned in [the online help](https://stackoverflow.com/help/duplicates) and [FAQ](https://meta.stackoverflow.com/q/252252/215552), to get it reopened? – Heretic Monkey May 02 '21 at 18:24

0 Answers0