aboutsummaryrefslogtreecommitdiff
path: root/src/hooks/interval.js
diff options
context:
space:
mode:
authorAlexander Kiryukhin <a.kiryukhin@mail.ru>2022-06-03 19:04:53 +0300
committerAlexander Kiryukhin <a.kiryukhin@mail.ru>2022-06-03 19:04:53 +0300
commit0e7b36c2d443306325f17bb8850f5bb6176202bf (patch)
tree86629d4fe05d73f2d77dad423cc37d5a612430f3 /src/hooks/interval.js
parent15d75cdc37e1459f7d11d004005d4305a6377ffd (diff)
initialHEADmaster
Diffstat (limited to 'src/hooks/interval.js')
-rw-r--r--src/hooks/interval.js26
1 files changed, 26 insertions, 0 deletions
diff --git a/src/hooks/interval.js b/src/hooks/interval.js
new file mode 100644
index 0000000..78f6e7b
--- /dev/null
+++ b/src/hooks/interval.js
@@ -0,0 +1,26 @@
+import { useEffect, useRef } from "react";
+
+const useInterval = (callback, interval, immediate) => {
+ const ref = useRef();
+ useEffect(() => {
+ ref.current = callback;
+ }, [callback]);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ const fn = () => {
+ ref.current(() => cancelled);
+ };
+
+ const id = setInterval(fn, interval);
+ if (immediate) fn();
+
+ return () => {
+ cancelled = true;
+ clearInterval(id);
+ };
+ }, [interval, immediate]);
+ };
+
+ export default useInterval;