useRandomInterval
Execute a callback function at a random interval with useRandomInterval.
Install:
Note: This hook depends on React’s experimental useEffectEvent.
npm i @uidotdev/usehooks@experimental react@experimental react-dom@experimental
Description:
The useRandomInterval hook is useful for executing a callback function at random intervals within a specified range. It provides a way to create an interval that varies dynamically based on minimum and maximum delay values. By using this hook, you can easily implement features such as periodic data updates, animations, or any other functionality that requires dynamic and random timing. The hook manages the interval internally, ensuring that it is cleared when the component unmounts or when the delay values change.
Parameters
Name | Type | Description |
---|---|---|
cb | function | The callback function to be executed at random intervals. |
options | object | An object containing the following options. |
options.minDelay | number | The minimum delay in milliseconds between each callback invocation. |
options.maxDelay | number | The maximum delay in milliseconds between each callback invocation. |
Return Value
Type | Description |
---|---|
function | A function to clear the timeout and stop the random interval execution. |
Demo:
Example:
import * as React from "react";
import { useRandomInterval } from "@uidotdev/usehooks";
import HeartsDemo from "./Heart";
export default function App() {
const demo = React.useRef(new HeartsDemo());
const clear = useRandomInterval(
() => {
demo.current.addHeart();
},
{ minDelay: 50, maxDelay: 3000 }
);
React.useEffect(() => {
demo.current.loop();
}, []);
return (
<section>
<h1>useRandomInterval</h1>
<button className="link" onClick={clear}>
Stop
</button>
</section>
);
}