Last active
September 7, 2021 09:24
-
-
Save ecklf/c5137cb9c7ea9af3ca9bd25c6efb20ca to your computer and use it in GitHub Desktop.
Revisions
-
ecklf renamed this gist
Sep 7, 2021 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
ecklf created this gist
Sep 7, 2021 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,71 @@ // Usage: // const Button = () => { // const { completion, ...bind } = useTimedEvent(() => { fire(); }, { duration: 1000 }); // return <button {...bind}>Button</button>; // }; import { useEffect, useRef, useState } from "react"; const useTimedEvent = ( callback: (() => void) | (() => Promise<void>), options?: { refreshRate?: number; duration?: number } ) => { const timerId = useRef<any>(null); const [progress, setProgress] = useState(0); const refreshRate = options?.refreshRate ?? 10; const triggerAt = (options?.duration ?? 1000) / refreshRate; const completion = (progress / triggerAt) * 100; useEffect(() => () => clearInterval(timerId.current), []); useEffect(() => { if (progress === triggerAt) { endProgress(); callback(); } }, [progress, triggerAt, callback]); const startProgress = () => { timerId.current = setInterval( () => setProgress((val) => val + 1), refreshRate ); }; const endProgress = () => { setProgress(0); clearInterval(timerId.current); }; const onMouseDown = () => { startProgress(); }; const onTouchStart = () => { startProgress(); }; const onMouseUp = () => { endProgress(); }; const onMouseOut = () => { endProgress(); }; const onTouchEnd = () => { endProgress(); }; return { completion, onMouseDown, onTouchStart, onMouseUp, onMouseOut, onTouchEnd, }; }; export default useTimedEvent;