useInterval
Execute a callback function at specific time intervals.
Features
- The interval is automatically cleared when the component is unmounted.
- You can temporarily pause the interval by setting the value of
delay
tonull
. - When the callback changes, the interval is not reset.
- When the
delay
changes, the interval is reset. - The interval is executed immediately on the first run, unless
immediate
is set tofalse
.
Installation
npm i @raddix/use-interval
Usage
Basic example
Create a counter that increments every second.
Pause and resume
Create a counter that increments every second, but can be paused and resumed.
API
Parameters
The hook accepts the following parameters:
Parameter | Description | Required | Type |
---|---|---|---|
func | The function to be executed each time the interval elapses. | Yes | function |
delay | The time, in milliseconds, the interval should wait before executing the function again. If `null`, the interval is paused. | Yes | number |
immediate | Whether the interval should be executed immediately on the first run. Defaults to `true`. | No | boolean |
Return value
The hook returns an object with the following properties:
Property | Description | Type |
---|---|---|
clear | A function that can be called to clear the interval. | function |
run | A function that can be called to execute the interval | function |