Skip to content

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

  • @template T Type of callback function parameters.

Props for the useInterval.

PropertyTypeRequiredDescription
callback(...args: T) => voidCallback executed on each interval tick.
delaynumberInterval period in milliseconds. The interval does not start automatically — call start() to begin.

UseIntervalResult

  • @template T Type of the callback function parameters.

Result tuple returned by useInterval.

IndexTypeDescription
[0](...args: T) => voidstart - function to start interval.
[1]() => voidstop - function to clear interval.
[2](...args: T) => Promise<void>promisify - function to promisify and start interval.

Released under the MIT License.