UNPKG

1.94 kBTypeScriptView Raw
1/**
2 * Creates a `setInterval` that is properly cleaned up when a component unmounted
3 *
4 * ```tsx
5 * function Timer() {
6 * const [timer, setTimer] = useState(0)
7 * useInterval(() => setTimer(i => i + 1), 1000)
8 *
9 * return <span>{timer} seconds past</span>
10 * }
11 * ```
12 *
13 * @param fn an function run on each interval
14 * @param ms The milliseconds duration of the interval
15 */
16declare function useInterval(fn: () => void, ms: number): void;
17/**
18 * Creates a pausable `setInterval` that is properly cleaned up when a component unmounted
19 *
20 * ```tsx
21 * const [paused, setPaused] = useState(false)
22 * const [timer, setTimer] = useState(0)
23 *
24 * useInterval(() => setTimer(i => i + 1), 1000, paused)
25 *
26 * return (
27 * <span>
28 * {timer} seconds past
29 *
30 * <button onClick={() => setPaused(p => !p)}>{paused ? 'Play' : 'Pause' }</button>
31 * </span>
32 * )
33 * ```
34 *
35 * @param fn an function run on each interval
36 * @param ms The milliseconds duration of the interval
37 * @param paused Whether or not the interval is currently running
38 */
39declare function useInterval(fn: () => void, ms: number, paused: boolean): void;
40/**
41 * Creates a pausable `setInterval` that _fires_ immediately and is
42 * properly cleaned up when a component unmounted
43 *
44 * ```tsx
45 * const [timer, setTimer] = useState(-1)
46 * useInterval(() => setTimer(i => i + 1), 1000, false, true)
47 *
48 * // will update to 0 on the first effect
49 * return <span>{timer} seconds past</span>
50 * ```
51 *
52 * @param fn an function run on each interval
53 * @param ms The milliseconds duration of the interval
54 * @param paused Whether or not the interval is currently running
55 * @param runImmediately Whether to run the function immediately on mount or unpause
56 * rather than waiting for the first interval to elapse
57 *
58
59 */
60declare function useInterval(fn: () => void, ms: number, paused: boolean, runImmediately: boolean): void;
61export default useInterval;