|
| 1 | +# useInterval |
| 2 | +Hook to handle setInterval timer function with the possibility to clear and promisify execution. |
| 3 | + |
| 4 | +## Usage |
| 5 | + |
| 6 | +```tsx |
| 7 | +export const UseInterval = () => { |
| 8 | + const [count, setCount] = useState(0); |
| 9 | + const [interval, setInterval] = useState(1000); |
| 10 | + const [apply, clear, applyPromisy] = useInterval( |
| 11 | + () => setCount(c => c + 1), |
| 12 | + interval |
| 13 | + ) |
| 14 | + |
| 15 | + return ( |
| 16 | + <div style={{ display: "grid", gridTemplateRows: "auto auto auto", justifyContent: "center", gap: 50 }}> |
| 17 | + <p>Count: {count}</p> |
| 18 | + <p>interval: {interval}</p> |
| 19 | + <div style={{ display: "grid", gridTemplateRows: "auto auto", gridTemplateColumns: "auto auto auto", justifyContent: "center", gap: 50 }}> |
| 20 | + <button onClick={apply}>Increment count</button> |
| 21 | + <button onClick={clear}>Clear Interval</button> |
| 22 | + <button onClick={async()=>applyPromisy().then(()=>setInterval(1000))}>Increment promisy</button> |
| 23 | + <button onClick={() => setInterval(d => d + 1000)}>Increment interval</button> |
| 24 | + <button onClick={() => setInterval(() => 1000)}>Clear interval</button> |
| 25 | + </div> |
| 26 | + </div> |
| 27 | + ); |
| 28 | +} |
| 29 | +``` |
| 30 | + |
| 31 | +> The component has: |
| 32 | +> - A _count_ state initialized to _0_. |
| 33 | +> - A _interval_ state initialized to _1000_. |
| 34 | +> - A _useInterval_ that receives a _callback_ to update _count_ by 1 and _interval_ as time to interval execution. |
| 35 | +> - Two p tag to diplay current _count_ and _interval_ variable. |
| 36 | +> - A button to execute _apply_ function returned from _useInterval_. |
| 37 | +> - A button to increment by 1000 _interval_ state. |
| 38 | +> - A button to restore _interval_ state to 1000. |
| 39 | +> - A button to execute _clear_ function returned from _useInterval_. |
| 40 | +> - A button to execute _applyPromisy_ function returned from _useInterval_ tha after _count_ state update, restore _interval_ state to 1000. |
| 41 | +
|
| 42 | + |
| 43 | +## API |
| 44 | + |
| 45 | +```tsx |
| 46 | +useInterval <TArgs extends unknown[]>(callback: (...args: TArgs) => void, delay: number): [(...args: TArgs) => void, () => void, (...args: TArgs) => Promise<void>] |
| 47 | +``` |
| 48 | +
|
| 49 | +> ### Params |
| 50 | +> |
| 51 | +> - __callback__: _(...args: unknown[])=>void_ |
| 52 | +Function to call when the timer elapses. |
| 53 | +> - __delay__: _number_ |
| 54 | +The number of milliseconds to wait before calling the `callback`. |
| 55 | +> |
| 56 | +
|
| 57 | +> ### Returns |
| 58 | +> |
| 59 | +> __- array: first element is the function to call setInterval; second element is the function to clearInterval; thrid element promisify setInterval.__ |
| 60 | +> - __Array__: |
| 61 | +> - _(...args: TArgs) => void, () => void, (...args: TArgs) => Promise<void>_ |
| 62 | +> |
0 commit comments