components
2 years ago
external-media
2 years ago
use-plan-type
2 years ago
use-ref-interval.ts
2 years ago
use-ref-interval.ts
68 lines
| 1 | import { useCallback, useEffect, useRef } from '@wordpress/element'; |
| 2 | |
| 3 | interface RafHandle { |
| 4 | id: number; |
| 5 | } |
| 6 | |
| 7 | const setRafInterval = ( callback: () => void, timeout: number = 0 ) => { |
| 8 | const interval = timeout < 0 ? 0 : timeout; |
| 9 | const handle: RafHandle = { |
| 10 | id: 0, |
| 11 | }; |
| 12 | |
| 13 | let startTime = Date.now(); |
| 14 | |
| 15 | const loop = () => { |
| 16 | const nowTime = Date.now(); |
| 17 | if ( nowTime - startTime >= interval ) { |
| 18 | startTime = nowTime; |
| 19 | callback(); |
| 20 | } |
| 21 | |
| 22 | handle.id = requestAnimationFrame( loop ); |
| 23 | }; |
| 24 | |
| 25 | handle.id = requestAnimationFrame( loop ); |
| 26 | |
| 27 | return handle; |
| 28 | }; |
| 29 | |
| 30 | const clearRafInterval = ( handle?: RafHandle | null ) => { |
| 31 | if ( handle ) { |
| 32 | cancelAnimationFrame( handle.id ); |
| 33 | } |
| 34 | }; |
| 35 | |
| 36 | /** |
| 37 | * Invoke a function on an interval that uses requestAnimationFrame. |
| 38 | * |
| 39 | * @param {Function} callback - Function to invoke |
| 40 | * @param {number} timeout - Interval timout in MS. |
| 41 | * |
| 42 | * @returns {Function} Function to clear the interval. |
| 43 | */ |
| 44 | const useRafInterval = ( callback: () => void, timeout = 0 ) => { |
| 45 | const timerRef = useRef< RafHandle >(); |
| 46 | |
| 47 | const callbackRef = useRef( callback ); |
| 48 | callbackRef.current = callback; |
| 49 | |
| 50 | useEffect( () => { |
| 51 | timerRef.current = setRafInterval( () => { |
| 52 | callbackRef.current(); |
| 53 | }, timeout ); |
| 54 | |
| 55 | return () => { |
| 56 | clearRafInterval( timerRef.current ); |
| 57 | }; |
| 58 | }, [ timeout ] ); |
| 59 | |
| 60 | const clear = useCallback( () => { |
| 61 | clearRafInterval( timerRef.current ); |
| 62 | }, [] ); |
| 63 | |
| 64 | return clear; |
| 65 | }; |
| 66 | |
| 67 | export default useRafInterval; |
| 68 |