useInterval
Hook to handle setInterval timer function with the possibility to clear and promisify execution.
Demo
INFO
The component has:
- A count state initialized to 0.
- A interval state initialized to 1000.
- A useInterval that receives a callback to update count by 1 and interval as time to interval execution.
- Two p tag to diplay current count and interval variable.
- A button to execute apply function returned from useInterval.
- A button to increment by 1000 interval state.
- A button to restore interval state to 1000.
- A button to execute clear function returned from useInterval.
- A button to execute applyPromisy function returned from useInterval tha after count state update, restore interval state to 1000.
Loading demo…
Show source code
tsx
import { useState } from "react"
import { useInterval } from "../../../..";
export const UseInterval = () => {
const [count, setCount] = useState(0);
const [interval, setInterval] = useState(1000);
const [apply, clear, applyPromisy] = useInterval(
() => setCount(c => c + 1),
interval
)
return (
<div style={{ display: "grid", gridTemplateRows: "auto auto auto", justifyContent: "center", gap: 50 }}>
<p>Count: {count}</p>
<p>interval: {interval}</p>
<div style={{ display: "grid", gridTemplateRows: "auto auto", gridTemplateColumns: "auto auto auto", justifyContent: "center", gap: 50 }}>
<button onClick={apply}>Increment count</button>
<button onClick={clear}>Clear Interval</button>
<button onClick={async()=>applyPromisy().then(()=>setInterval(1000))}>Increment promisy</button>
<button onClick={() => setInterval(d => d + 1000)}>Increment interval</button>
<button onClick={() => setInterval(() => 1000)}>Clear interval</button>
</div>
</div>
);
}Types
UseIntervalProps
@templateT Type of callback function parameters.
Props for the useInterval.
| Property | Type | Required | Description |
|---|---|---|---|
callback | (...args: T) => void | ✓ | Callback executed on each interval tick. |
delay | number | ✓ | Interval period in milliseconds. The interval does not start automatically — call start() to begin. |
UseIntervalResult
@templateT Type of the callback function parameters.
Result tuple returned by useInterval.
| Index | Type | Description |
|---|---|---|
[0] | (...args: T) => void | start - function to start interval. |
[1] | () => void | stop - function to clear interval. |
[2] | (...args: T) => Promise<void> | promisify - function to promisify and start interval. |
