如何使用React钩子在光标停止移动3秒后触发功能?

时间:2019-12-05 06:30:00

标签: reactjs react-hooks

我只是在探索钩子,但我不知道在光标停止移动3秒后要触发一个函数我必须使用什么逻辑

我的尝试

const handleMouseMove = () => {
        console.log('I don't know what to do ???')

    };
    useEffect(() => {
        window.addEventListener("mousemove", handleMouseMove);
        return () => {
            window.removeEventListener("mousemove", handleMouseMove);
        };
    },[]);

2 个答案:

答案 0 :(得分:1)

let timer = null;

const handleMouseMove = () => {
  if (timer) clearTimeout(timer);
  timer = setTimeout(() => {
    // do your things...
  }, 3000);
};

追加:

在您的useEffect callback中,您应该清除此timer以避免超时回调。

useEffect(() => {
  window.addEventListener("mousemove", handleMouseMove);
  return () => {
    window.removeEventListener("mousemove", handleMouseMove);
    if (timer) clearTimeout(timer);
  };
},[]);

答案 1 :(得分:0)

如评论中所述,以下是我的尝试,希望它对您有用

function  MouseTracker (props) {
    const [lastMoveTime, setLastMoveTime] = useState(new Date().getTime() / 1000);
    const [curMoveTime, setCurMoveTime] = useState(new Date().getTime() / 1000);

   function handleMouseMove(event){
     setLastMoveTime(new Date().getTime() / 1000);
   }
   const timeTrack=setInterval(function(){
    let curMoveTime=new Date().getTime() / 1000;
    if(curMoveTime-lastMoveTime >= 3){
        //trigger the function call
    }else{
        //or updat the curmove time
        setCurMoveTime(curMoveTime)
    }
},100)
//
return <YourComponentCode/>
}