Skip to content

Instantly share code, notes, and snippets.

@takumifukasawa
Last active November 5, 2020 01:07
Show Gist options
  • Save takumifukasawa/3785ae0f80845f76eb9664b45784e28b to your computer and use it in GitHub Desktop.
Save takumifukasawa/3785ae0f80845f76eb9664b45784e28b to your computer and use it in GitHub Desktop.
React: manage window timeout custom hooks
import { useEffect, useRef } from "react";
/**
* manage window timeout hooks
*
* ex)
*
* const [beginTimer, clearTimer] = useTimeout(() => { ... }, ms);
*
* useEffect(() => {
* beginTimer();
* }, [deps1]);
*
* useEffect(() => {
* clearTimer();
* }, [deps2]);
*
* @export
* @param {() => void | null} exec
* @param {number} ms
* @returns
*/
export default function useTimeout(
exec: (() => void) | null,
ms: number
): [() => void, () => void] {
const timerId = useRef<number | null>(null);
const clearTimer = () => {
if (timerId.current) {
window.clearTimeout(timerId.current);
timerId.current = null;
}
};
const beginTimer = () => {
clearTimer();
timerId.current = window.setTimeout(() => {
if (exec) {
exec();
}
clearTimer();
}, ms);
};
useEffect(() => {
return () => clearTimer();
}, []);
return [beginTimer, clearTimer];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment