Last active: a year ago
Detect idle when browser lose focus.
import { useCallback, useEffect, useRef } from 'react';
const MINUTE = 60 * 1000;
/**
* 空闲检测
*
* 当浏览器丢失焦点时,出发定时器;定时结束后执行回调函数。
*
* 回调函数 `callback` 是 `useCallback` 的依赖,需要保持地址唯一。
*
* @param timeout 超时时长 默认 5 分钟
* @param callback 回调
*/
const useIdle = (
timeout = MINUTE * 5,
callback = () => {
console.warn('idled');
}
) => {
const id = useRef<NodeJS.Timeout>();
const handleVisibilty = useCallback(
(e: Event) => {
const map = {
blur: () => {
id.current = setTimeout(callback, timeout);
},
focus: () => {
clearTimeout(id.current);
},
};
map?.[e.type]?.();
},
[callback, timeout]
);
useEffect(() => {
window.addEventListener('blur', handleVisibilty);
window.addEventListener('focus', handleVisibilty);
return () => {
window.removeEventListener('blur', handleVisibilty);
window.removeEventListener('focus', handleVisibilty);
};
}, [handleVisibilty]);
};
export default useIdle;