2020-07-24 16:17:03 +02:00
|
|
|
import { useState, useEffect, useRef, useCallback } from 'react'
|
|
|
|
|
|
|
|
/**
|
|
|
|
* useTimeout
|
|
|
|
*
|
|
|
|
* @param {Function} cb - callback function inside setTimeout
|
|
|
|
* @param {number} delay - delay in ms
|
|
|
|
* @param {boolean} [immediate] - determines whether the timeout is invoked immediately
|
|
|
|
*
|
2020-08-12 21:06:57 +02:00
|
|
|
* @return {Function|undefined}
|
2020-07-24 16:17:03 +02:00
|
|
|
*/
|
|
|
|
export function useTimeout (cb, delay, immediate = true) {
|
|
|
|
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
|
|
|
|
}
|