1

Using React: I have this initial eventListener that listens for mousemove inside my video element then what I want to listen for is a code that detects when the mouse has stopped moving to start a timer like this:

// initial listener 
useEffect(() => {
        vidRef.current.addEventListener('mousemove', displayOpa)
        
        return () => {
            vidRef.current.removeEventListener('mousemove', displayOpa)
        }
    }, [])

the function displayOpa:

const displayOpa = () => {
        controlsBackgroundRef.current.style.opacity = 1;
        vidControlsRef.current.style.opacity = 1;
        

        // basically here I want to start this timer when the mouse has stopped moving only how would I say that?
        // like 
       if ("mouse has stopped moving then run code below") {
        const initialSwitch = setTimeout(() => {
            controlsBackgroundRef.current.style.opacity = 0;
            vidControlsRef.current.style.opacity = 0;
        }, 5000)
      }
    }
Mohamed
  • 425
  • 4
  • 14
  • Have you tried something like described here? -https://stackoverflow.com/questions/15066849/how-to-detect-when-mousemove-has-stopped – Nikita Chayka Jul 01 '21 at 14:46

1 Answers1

2

you can just clean timeout on every mouse move, so when the user stops moving the reset style function will be invoked:


useEffect(() => {
  let timeout = 0;

  const displayOpa = () => {
    controlsBackgroundRef.current.style.opacity = 1;
    vidControlsRef.current.style.opacity = 1;

    clearTimeout(timeout);

    timeout = setTimeout(() => {
      controlsBackgroundRef.current.style.opacity = 0;
      vidControlsRef.current.style.opacity = 0;
    }, 5000);
  };

  vidRef.current.addEventListener('mousemove', displayOpa);

  return () => {
    vidRef.current.removeEventListener('mousemove', displayOpa);
  };
}, []);