Search code examples
reactjssettimeoutaddeventlistenercleartimeoutremoveeventlistener

listen for when mouse has stopped moving


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)
      }
    }

Solution

  • 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);
      };
    }, []);