Home > Back-end >  React setInterval with useEffect not stopping
React setInterval with useEffect not stopping

Time:10-30

I am basically trying to count from 0 to 100 at a specific speed.

so, I have the following:

useEffect(() => {
    const interval = setInterval(() => {
        setProgress((progress) => progress   1);
        if (progress === 100) {
            clearInterval(interval);
        }
    }, 16);
    return () => clearInterval(interval);
}, []);
console.log(progress);

Now when I load my component, in the console the count does not stop, it keeps going over 100. How do I stop it when the progress reaches 100?

CodePudding user response:

If you console log the progress value inside the useEffect you can see why it is not stopping.
try something like this to get it working:

useEffect(() => {
    const timeout = setTimeout(() => {
      setProgress(progress => progress   1);
    }, 16);
    if (progress === 100) {
      clearTimeout(timeout);
    }
    return () => clearTimeout(timeout);
  }, [progress]);
console.log(progress);

CodePudding user response:

import "./styles.css";
import { useEffect, useState, useRef } from "react";

export default function App() {
  const [progress, setProgress] = useState(0);
  let interval = useRef();
  useEffect(() => {
    interval.current = setInterval(() => {
      setProgress((progress) => progress   1);
    }, 16);
    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    if (progress === 100) {
      clearInterval(interval.current);
    }
  }, [progress]);

  console.log(progress);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

this is my take. Using ref and 2 useEffects. https://codesandbox.io/s/runtime-pine-5xntw?file=/src/App.js:0-639

  • Related