useCountDown
Manage a countdown with options to start, stop and reset.
Features
- Execute a function when the timer has expired.
- Start the countdown immediately or manually.
Installation
Install the custom hook from the command line.
npm i @raddix/use-count-down
Usage
Basic example
This example showcases how you could setup a timer for your application.
Callbacks based on the countdown state
You could setup two callbacks to get called on certain countdown states.
onFinished
: Gets called when the countdown reaches zero.onTick
: Gets called on each countdown interval.
API
Return Value
Returns an array that can be destructured into two variables: count and actions. These are reference names, so you can name them as you wish.
Index | Description | Type |
---|---|---|
0 (count)) | The current value of the countdown timer. It will stop when it reaches 0. | number |
1 (actions) | An object containing timer manipulation methods. | Object |
Action Functions
Name | Description | Type |
---|---|---|
start | Starts the timer if it's stopped or configured with `autoStart: false`. It can optionally define a new initial time by passing it as prop. This is useful if you need to add another one second to the timer. | function |
stop | Stops the timer. | function |
reset | Resets the timer count value. If the timer was configured with `autoStart: true`, it will restart immediately. | function |
Parameters
The useCountDown
hook takes two setup values.
Name | Description | Required | Type |
---|---|---|---|
initialTime | Countdown initial value. It is expressed in miliseconds. | Yes | number |
options | Countdown configuration object. | No | Object |
Configuration Options
Name | Description | Required | Default Value | Type |
---|---|---|---|---|
interval | Time interval for refresing the count value. IMPORTANT: This interval doesn't affect the countdown rate. This is useful if you need to refresh at a slow (~1 second) or fast (~10ms) rate. | No | 1000 | number |
autoStart | Specifies whether the timer should start automatically after being set. | No | true | boolean |
onFinished | Callback to be executed when the count value reaches 0. | No | undefined | function |
onTick | Callback to be executed on each count value refresh. | No | undefined | function |