Calls given function after specified amount of milliseconds.
Several thing about it's work:
- does not re-render component;
- automatically cancel timeout on cancel;
- automatically reset timeout on delay change;
- reset function call will cancel previous timeout;
- timeout will NOT be reset on function change. It will be called within the timeout, you have to reset it on your own when needed.
import * as React from 'react';
import { useTimeoutFn } from 'react-use';
const Demo = {
setup() {
const [state, setState] = useState('Not called yet');
function fn() {
setState(`called at ${Date.now()}`);
}
const [isReady, cancel, reset] = useTimeoutFn(fn, 5000);
const cancelButtonClick = () => {
if (isReady.value === false) {
cancel();
setState(`cancelled`);
} else {
reset();
setState('Not called yet');
}
};
return () => (
<div>
<div>{isReady.value !== null ? 'Function will be called in 5 seconds' : 'Timer cancelled'}</div>
<button onClick={cancelButtonClick}>
{' '}
{isReady.value === false ? 'cancel' : 'restart'} timeout
</button>
<br/>
<div>
Function state: {isReady.value === false ? 'Pending' : isReady.value ? 'Called' : 'Cancelled'}
</div>
<div>{state.value}</div>
</div>
);
}
};
const [
isReady: Computed<boolean | null>,
cancel: () => void,
reset: () => void,
] = useTimeoutFn(fn: Function, ms: number = 0);
fn
: Function
- function that will be called;ms
: number
- delay in milliseconds;isReady
: Computed<boolean | null>
- function returning current timeout state:false
- pendingtrue
- callednull
- cancelled
cancel
: ()=>void
- cancel the timeoutreset
: ()=>void
- reset the timeout