1 | "use strict";
|
2 |
|
3 | exports.__esModule = true;
|
4 | exports.default = useTimeout;
|
5 | var _react = require("react");
|
6 | var _useMounted = _interopRequireDefault(require("./useMounted"));
|
7 | var _useWillUnmount = _interopRequireDefault(require("./useWillUnmount"));
|
8 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const MAX_DELAY_MS = 2 ** 31 - 1;
|
18 | function setChainedTimeout(handleRef, fn, timeoutAtMs) {
|
19 | const delayMs = timeoutAtMs - Date.now();
|
20 | handleRef.current = delayMs <= MAX_DELAY_MS ? setTimeout(fn, delayMs) : setTimeout(() => setChainedTimeout(handleRef, fn, timeoutAtMs), MAX_DELAY_MS);
|
21 | }
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 | function useTimeout() {
|
42 | const isMounted = (0, _useMounted.default)();
|
43 |
|
44 |
|
45 | const handleRef = (0, _react.useRef)();
|
46 | (0, _useWillUnmount.default)(() => clearTimeout(handleRef.current));
|
47 | return (0, _react.useMemo)(() => {
|
48 | const clear = () => clearTimeout(handleRef.current);
|
49 | function set(fn, delayMs = 0) {
|
50 | if (!isMounted()) return;
|
51 | clear();
|
52 | if (delayMs <= MAX_DELAY_MS) {
|
53 |
|
54 | handleRef.current = setTimeout(fn, delayMs);
|
55 | } else {
|
56 | setChainedTimeout(handleRef, fn, Date.now() + delayMs);
|
57 | }
|
58 | }
|
59 | return {
|
60 | set,
|
61 | clear
|
62 | };
|
63 | }, []);
|
64 | } |
\ | No newline at end of file |