简体   繁体   中英

Facing issue while updating auto increment counter value in react.js using useEffect Hook

I'm having an issue with the auto-increment counter, which updates every 2 secs. It updates the value but in a glitchy way Please check the code and share your views regarding the problem.

 const [counter, setCounter] = useState(1200)
 function handleCounter() {
    setCounter(counter + 1)
}
useEffect(() => {
    if (counter => 1200 && counter < 1364) {
        setInterval(handleCounter, 2000);
    }else {
        clearInterval(setInterval(handleCounter, 2000))
    }
    clearInterval(setInterval(handleCounter, 2000))
}, [counter])

try this

useEffect(() => {
    const timeInterval = setInterval(() => {
      counter < 1364 && setCounter((prevCount) => prevCount + 1);
    }, 2000);

    return () => {
      clearInterval(timeInterval);
    };
  }, [counter]);

The code below will execute the handleCounter function every 2 seconds. Is it what you are trying to do?

  useEffect(() => {
    const intervalID = setInterval(() => handleCounter(), 2000);
    return () => {
      clearInterval(intervalID);
    }
  },[]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM