main
Last change
on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago |
Update repo after prototype presentation
|
-
Property mode
set to
100644
|
File size:
986 bytes
|
Line | |
---|
1 | import { useCallback, useEffect, useRef } from 'react';
|
---|
2 | export default function useTimeoutFn(fn, ms) {
|
---|
3 | if (ms === void 0) { ms = 0; }
|
---|
4 | var ready = useRef(false);
|
---|
5 | var timeout = useRef();
|
---|
6 | var callback = useRef(fn);
|
---|
7 | var isReady = useCallback(function () { return ready.current; }, []);
|
---|
8 | var set = useCallback(function () {
|
---|
9 | ready.current = false;
|
---|
10 | timeout.current && clearTimeout(timeout.current);
|
---|
11 | timeout.current = setTimeout(function () {
|
---|
12 | ready.current = true;
|
---|
13 | callback.current();
|
---|
14 | }, ms);
|
---|
15 | }, [ms]);
|
---|
16 | var clear = useCallback(function () {
|
---|
17 | ready.current = null;
|
---|
18 | timeout.current && clearTimeout(timeout.current);
|
---|
19 | }, []);
|
---|
20 | // update ref when function changes
|
---|
21 | useEffect(function () {
|
---|
22 | callback.current = fn;
|
---|
23 | }, [fn]);
|
---|
24 | // set on mount, clear on unmount
|
---|
25 | useEffect(function () {
|
---|
26 | set();
|
---|
27 | return clear;
|
---|
28 | }, [ms]);
|
---|
29 | return [isReady, clear, set];
|
---|
30 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.