Skip to content

Instantly share code, notes, and snippets.

@GeeWizWow
Last active June 5, 2024 19:38
Show Gist options
  • Save GeeWizWow/eaae7cbed218843d7084c7a87985efd3 to your computer and use it in GitHub Desktop.
Save GeeWizWow/eaae7cbed218843d7084c7a87985efd3 to your computer and use it in GitHub Desktop.
use-idle.ts
import { useIdle } from './use-idle-detection';
import { useSpring, animated } from '@react-spring/web';
export default function Home() {
const { isIdle } = useIdle({ activity: 3000, leave: 300 });
const springProps = useSpring({ opacity: isIdle ? 0 : 1 });
return (
<animated.main style={springProps}>
</animated.main>
);
}
export const throttle = (cb: (...args: any[]) => void, ms: number) => {
let lastTime = 0;
return (...args: Parameters<typeof cb>) => {
const now = Date.now();
if (now - lastTime >= ms) {
lastTime = now;
cb(...args);
}
};
};
import { useEffect, useRef, useCallback, useState } from 'react';
import { throttle } from './throttle';
export interface UseIdleProps {
activity: number;
leave: number;
}
export const useIdle = ({ activity, leave }: UseIdleProps) => {
const idleTimeoutRef = useRef<number>();
const [isIdle, setIsIdle] = useState<boolean>(false);
const handleTimeout = useCallback(() => setIsIdle(true), []);
const handleEvent = useCallback(throttle(() => {
setIsIdle(false);
window.clearTimeout(idleTimeoutRef.current);
idleTimeoutRef.current = window.setTimeout(handleTimeout, activity);
}, 500), []);
const handleLeave = useCallback(() => {
window.clearTimeout(idleTimeoutRef.current);
idleTimeoutRef.current = window.setTimeout(handleTimeout, leave);
}, []);
const handleVisibilityChange = useCallback(() => {
if (!document.hidden) {
handleEvent();
}
}, []);
useEffect(() => {
window.addEventListener('mousemove', handleEvent);
window.addEventListener('mousedown', handleEvent);
window.addEventListener('resize', handleEvent);
window.addEventListener('keydown', handleEvent);
window.addEventListener('touchstart', handleEvent);
window.addEventListener('wheel', handleEvent);
document.addEventListener('mouseleave', handleLeave);
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
window.removeEventListener('mousemove', handleEvent);
window.removeEventListener('mousedown', handleEvent);
window.removeEventListener('resize', handleEvent);
window.removeEventListener('keydown', handleEvent);
window.removeEventListener('touchstart', handleEvent);
window.removeEventListener('wheel', handleEvent);
document.removeEventListener('mouseleave', handleLeave);
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);
return { isIdle };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment