2020-07-24 16:17:03 +02:00
|
|
|
import { useState, useEffect, useRef, useCallback } from 'react'
|
|
|
|
|
|
|
|
/**
|
|
|
|
* useTimeout
|
|
|
|
*
|
2020-11-10 18:30:41 +01:00
|
|
|
* @param {Function} cb - callback function inside setTimeout
|
|
|
|
* @param {number} delay - delay in ms
|
|
|
|
* @param {boolean} [immediate] - determines whether the timeout is invoked immediately
|
2020-07-24 16:17:03 +02:00
|
|
|
*
|
2020-08-12 21:06:57 +02:00
|
|
|
* @return {Function|undefined}
|
2020-07-24 16:17:03 +02:00
|
|
|
*/
|
2020-11-03 00:41:28 +01:00
|
|
|
export function useTimeout(cb, delay, immediate = true) {
|
2020-07-24 16:17:03 +02:00
|
|
|
const saveCb = useRef()
|
|
|
|
const [timeoutId, setTimeoutId] = useState(null)
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
saveCb.current = cb
|
|
|
|
}, [cb])
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (timeoutId !== 'start') {
|
2020-08-12 21:06:57 +02:00
|
|
|
return undefined
|
2020-07-24 16:17:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const id = setTimeout(() => {
|
|
|
|
saveCb.current()
|
|
|
|
}, delay)
|
|
|
|
|
|
|
|
setTimeoutId(id)
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
clearTimeout(timeoutId)
|
|
|
|
}
|
|
|
|
}, [delay, timeoutId])
|
|
|
|
|
|
|
|
const startTimeout = useCallback(() => {
|
|
|
|
clearTimeout(timeoutId)
|
|
|
|
setTimeoutId('start')
|
|
|
|
}, [timeoutId])
|
|
|
|
|
|
|
|
if (immediate) {
|
|
|
|
startTimeout()
|
|
|
|
}
|
|
|
|
|
|
|
|
return startTimeout
|
|
|
|
}
|