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

NameTypeDescriptionDefault ValueOptional
cbFunctionThe callback function to be executed at the specified interval when the condition is met.-No
optionsobjectAn object containing the following options.-Yes
options.msnumberThe interval duration in milliseconds.-Yes
options.whenbooleanThe condition that determines whether the interval should be active (true) or paused (false).falseYes
options.startImmediatelyboolean(Optional) Whether to start the interval immediately when the condition is met. Default is false.falseYes

Return Values

TypeDescription
FunctionA function to clear the interval and pause the execution.