Can't change a variable in React because of this

I am capturing poses every second, but when I change the state of the variable, the site crashes, console.log() goes crazy fast, 10-20 times in a second.

Shortened code:

const runPose = async () => {
    const detector = await poseDetection.createDetector(
      poseDetection.SupportedModels.MoveNet, 
      {modelType: poseDetection.movenet.modelType.SINGLEPOSE_THUNDER,}
    );
    setInterval(() => {detect(detector)}, 1000); // This function's the problem
  };

Problem:

const detect = async (net: any) => {
      const poses = await net.estimatePoses(video);
      const kp = poses[0].keypoints
      const sum = Math.abs(kp[6].y - kp[12].y)
      setstate(sum) // if I don't do this, the website's fine. 
      // if I do, console.log() happens 10-20 times a second
      console.log('hi')
}
function App() {
     runPose();
}

Hi @Mishka_Musaeliani ,

I apologize for the late response. I think you’re using the runPose() within a react useEffect hook. So, if there’s any change in the component caused by setState(sum), it will re-call the runPose() function, which in turn calls setInterval again. This is why the function is being called multiple times.

You could either place the runPose() function outside the useEffect hook to invoke it only once, or you could remove the setInterval(() => {detect(detector)}, 1000); function and use setTimeout at the beginning of runPose().

Change:

const runPose = async () => {
   const timeOut = setTimeout(() => detect(detector), 1000)
    const detector = await poseDetection.createDetector(
      poseDetection.SupportedModels.MoveNet, 
      {modelType: poseDetection.movenet.modelType.SINGLEPOSE_THUNDER,}
    );
  clearTimeout(timeOut);

  }

Let me know if this helps. Thank you!