useIntervalWhen
Create dynamic timers that can be started, paused, or resumed with useIntervalWhen.
Install:
Note: This hook depends on React’s experimental useEffectEvent.
npm i @uidotdev/usehooks@experimental react@experimental react-dom@experimental
Description:
The useIntervalWhen hook is useful for creating an interval timer that can be controlled based on certain conditions. It allows you to specify a callback function to be executed at a regular interval specified by the ms parameter. Additionally, you can choose whether the interval should start immediately or wait for a trigger by setting the startImmediately parameter. This hook is particularly handy when you need to create dynamic timers that can be started, paused, or resumed based on specific conditions.
Parameters
Name | Type | Description |
---|---|---|
cb | function | The callback function to be executed at the specified interval when the condition is met. |
options | object | An object containing the following options. |
options.ms | number | The interval duration in milliseconds. |
options.when | boolean | The condition that determines whether the interval should be active (true ) or paused (false ). |
options.startImmediately | boolean | (Optional) Whether to start the interval immediately when the condition is met. Default is false . |
Return Value
Type | Description |
---|---|
function | A function to clear the interval and pause the execution. |
Demo:
Example:
import * as React from "react";
import { useIntervalWhen } from "@uidotdev/usehooks";
export default function App() {
const [count, setCount] = React.useState(0);
const [when, setWhen] = React.useState(false);
useIntervalWhen(
() => {
setCount((c) => c + 0.1);
},
{ ms: 100, when, startImmediately: true }
);
return (
<section>
<h1>useIntervalWhen</h1>
<button title="Click to toggle the timer" onClick={() => setWhen(!when)}>
{count.toLocaleString("en-US", {
maximumFractionDigits: 2,
minimumFractionDigits: 2,
})}
<span className="btn link">{when ? "stop" : "start"}</span>
</button>
</section>
);
}