If the external value changes in the middle of setInterval or setTimeout, I want to recognize it and stop setInterval or setTimeout

Viewed 28

 import React, {useState} from 'react';
 
 //...
    const [isPreparationTime, setIsPreparationTime] = useState(true);


  useEffect(() => {
    if (isPreparationTime) {
      runPosenet();
    }
  }, [isPreparationTime]);
  
  
  const runPosenet = async () => {
    const net = await posenet.load({
      inputResolution: { width: 640, height: 480 },
      scale: 0.8,
    });

    const temp = setInterval(() => {
      detect(net);
    }, 1000);

    setTimeout(() => clearInterval(temp) & console.log("done"), 3000);
  };
  
  const detect = async (net) => {
    if (
      typeof firstParticipantRef.current !== "undefined" &&
      firstParticipantRef.current !== null &&
      firstParticipantRef.current.video.readyState === 4
    ) {
      const firstVideo = videoReference(firstParticipantRef);
      const secondVideo = videoReference(secondParticipantRef);

      const firstVideoPose = await net.estimateSinglePose(firstVideo);
      const secondVideoPose = await net.estimateSinglePose(secondVideo);

      drawCanvas(
        firstVideoPose,
        firstVideo,
        firstVideo.width,
        firstVideo.height,
        firstCanvas
      );
      drawCanvas(
        secondVideoPose,
        secondVideo,
        secondVideo.width,
        secondVideo.height,
        secondCanvas
      );

      if (isReady) {
        addFirstParticipantPose(firstVideoPose);
        addSecondParticipantPose(secondVideoPose);
      } else {
        addPreStartFirstParticipantPose(firstVideoPose);
        addPreStartSecondparticipantPose(secondVideoPose);
      }
    }
  };
  //...

I want setInterval to exit before setTimeout is finished. I've tried clearTimeout or clearInterval, but it doesn't work because it's inside an async function.

I wanted to quit when isPreparationTime becomes false, so I wrote if(!isPreparation) { clearInterval(temp)} in setInterval, but it does not work. I don't know what to do. Please help.

0 Answers
Related