File size: 1,133 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useRef } from 'react';
import type { TimeoutMS } from 'calypso/types';

/**
 * useInterval implementation from @see https://overreacted.io/making-setinterval-declarative-with-react-hooks/
 *
 * Used with explicit permission:
 * > Feel free to copy paste it in your project or put it on npm.
 * https://github.com/gaearon/overreacted.io/blob/80c0a314c5d855891220852788f662c2e8ecc7d4/src/pages/making-setinterval-declarative-with-react-hooks/index.md
 */

/**
 * Invoke a function on an interval.
 * @param callback Function to invoke
 * @param delay    Interval timout in MS. `null` or `false` to stop the interval.
 */
export function useInterval( callback: () => void, delay: TimeoutMS | null | false ) {
	const savedCallback = useRef( callback );

	// Remember the latest callback.
	useEffect( () => {
		savedCallback.current = callback;
	}, [ callback ] );

	// Set up the interval.
	useEffect( () => {
		if ( delay === null || delay === false ) {
			return;
		}
		const tick = () => void savedCallback.current();
		const id = setInterval( tick, delay );
		return () => clearInterval( id );
	}, [ delay ] );
}