-
Notifications
You must be signed in to change notification settings - Fork 12
/
use-random-interval.tsx
42 lines (35 loc) · 1014 Bytes
/
use-random-interval.tsx
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
import { useCallback, useEffect, useRef } from 'react'
import { random } from '@/utils'
export function useRandomInterval({
callback,
minDelay,
maxDelay
}: {
callback: () => void
minDelay: number | null
maxDelay: number | null
}) {
const timeoutId = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
const savedCallback = useRef(callback)
useEffect(() => {
savedCallback.current = callback
}, [callback])
useEffect(() => {
const isEnabled = typeof minDelay === 'number' && typeof maxDelay === 'number'
if (isEnabled) {
const handleTick = () => {
const nextTickAt = random({ min: minDelay, max: maxDelay })
timeoutId.current = setTimeout(() => {
savedCallback.current()
handleTick()
}, nextTickAt)
}
handleTick()
}
return () => clearTimeout(timeoutId.current)
}, [minDelay, maxDelay])
const cancel = useCallback(function () {
clearTimeout(timeoutId.current)
}, [])
return cancel
}