Docs
useIntervalWhen
Create dynamic timers that can be started, paused, or resumed with useIntervalWhen.
Loading...
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-interval-when
Usage
"use client"
import * as React from "react"
import { useIntervalWhen } from "@/hooks/use-interval-when"
export function Component() {
const [count, setCount] = useState(0)
const [isActive, setIsActive] = useState(false)
const clearInterval = useIntervalWhen(
() => {
setCount((c) => c + 1)
},
{
ms: 1000,
when: isActive,
startImmediately: true,
}
)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setIsActive((a) => !a)}>
{isActive ? "Pause" : "Start"}
</button>
<button onClick={clearInterval}>Clear</button>
</div>
)
}
API Reference
Parameters
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
cb | Function | The callback function to be executed at the specified interval when the condition is met. | - | No |
options | object | An object containing the following options. | - | Yes |
options.ms | number | The interval duration in milliseconds. | - | Yes |
options.when | boolean | The condition that determines whether the interval should be active (true ) or paused (false ). | false | Yes |
options.startImmediately | boolean | (Optional) Whether to start the interval immediately when the condition is met. Default is false . | false | Yes |
Return Values
Type | Description |
---|---|
Function | A function to clear the interval and pause the execution. |