useIntervalWhen
A hook that sets an interval that can be enabled or disabled.
The useIntervalWhen hook is a wrapper around setInterval that allows you to easily enable or disable the interval using a boolean flag. It also supports executing the callback immediately when the interval starts.
Demo
0
Interval Speed100ms
Source Code
Copy this code into src/hooks/useIntervalWhen.ts:
import { useEffect, useRef } from 'react';
export const useIntervalWhen = (
callback: () => void,
ms: number,
when: boolean,
startImmediately: boolean = false,
) => {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
if (!when) return;
if (startImmediately) {
savedCallback.current();
}
const interval = setInterval(() => {
savedCallback.current();
}, ms);
return () => clearInterval(interval);
}, [ms, when, startImmediately]);
};Usage
import { useState } from 'react';
import { useIntervalWhen } from '@/hooks/useIntervalWhen';
const TimerComponent = () => {
const [count, setCount] = useState(0);
const [enabled, setEnabled] = useState(false);
useIntervalWhen(
() => {
setCount((prev) => prev + 1);
},
1000, // 1 second
enabled, // only run when true
true, // start immediately
);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setEnabled(!enabled)}>{enabled ? 'Stop' : 'Start'}</button>
</div>
);
};API Reference
Parameters
| Name | Type | Description |
|---|---|---|
callback | () => void | The function to be executed at each interval. |
ms | number | The duration in milliseconds between executions. |
when | boolean | A flag to enable or disable the interval. |
startImmediately | boolean | (Optional) Whether to execute the callback immediately when enabled. Default is false. |