Loading...
Please waitLoading...
Please waitpnpm dlx uselab@latest add use-interval-when
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>
)
}| 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 |
| Type | Description |
|---|---|
Function | A function to clear the interval and pause the execution. |