about summary refs log tree commit diff
path: root/src/lib/hooks
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/hooks')
-rw-r--r--src/lib/hooks/useTimer.ts32
1 files changed, 32 insertions, 0 deletions
diff --git a/src/lib/hooks/useTimer.ts b/src/lib/hooks/useTimer.ts
new file mode 100644
index 000000000..bf3ecc07f
--- /dev/null
+++ b/src/lib/hooks/useTimer.ts
@@ -0,0 +1,32 @@
+import * as React from 'react'
+
+/**
+ * Helper hook to run persistent timers on views
+ */
+export function useTimer(time: number, handler: () => void) {
+  const timer = React.useRef(undefined)
+
+  // function to restart the timer
+  const reset = React.useCallback(() => {
+    if (timer.current) {
+      clearTimeout(timer.current)
+    }
+    timer.current = setTimeout(handler, time)
+  }, [time, timer, handler])
+
+  // function to cancel the timer
+  const cancel = React.useCallback(() => {
+    if (timer.current) {
+      clearTimeout(timer.current)
+      timer.current = undefined
+    }
+  }, [timer])
+
+  // start the timer immediately
+  React.useEffect(() => {
+    reset()
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [])
+
+  return [reset, cancel]
+}