forked from streamich/react-use
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseIdle.ts
57 lines (46 loc) · 1.39 KB
/
useIdle.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* eslint-disable */
import { useEffect, useState } from 'react';
import { throttle } from 'throttle-debounce';
import { off, on } from './util';
const defaultEvents = ['mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel'];
const oneMinute = 60e3;
const useIdle = (ms: number = oneMinute, initialState: boolean = false, events: string[] = defaultEvents): boolean => {
const [state, setState] = useState<boolean>(initialState);
useEffect(() => {
let mounted = true;
let timeout: any;
let localState: boolean = state;
const set = (newState: boolean) => {
if (mounted) {
localState = newState;
setState(newState);
}
};
const onEvent = throttle(50, () => {
if (localState) {
set(false);
}
clearTimeout(timeout);
timeout = setTimeout(() => set(true), ms);
});
const onVisibility = () => {
if (!document.hidden) {
onEvent();
}
};
for (let i = 0; i < events.length; i++) {
on(window, events[i], onEvent);
}
on(document, 'visibilitychange', onVisibility);
timeout = setTimeout(() => set(true), ms);
return () => {
mounted = false;
for (let i = 0; i < events.length; i++) {
off(window, events[i], onEvent);
}
off(document, 'visibilitychange', onVisibility);
};
}, [ms, events]);
return state;
};
export default useIdle;