I am just exploring hooks but I don't know what logic I have to use in order to trigger a function after cursor stopped moving for 3 seconds
My try
const handleMouseMove = () => {
console.log('I don't know what to do ???')
};
useEffect(() => {
window.addEventListener("mousemove", handleMouseMove);
return () => {
window.removeEventListener("mousemove", handleMouseMove);
};
},[]);
let timer = null;
const handleMouseMove = () => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
// do your things...
}, 3000);
};
Append:
in your useEffect callback
, you should clear this timer
to avoid timeout callback.
useEffect(() => {
window.addEventListener("mousemove", handleMouseMove);
return () => {
window.removeEventListener("mousemove", handleMouseMove);
if (timer) clearTimeout(timer);
};
},[]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With