Created
January 11, 2024 21:07
-
-
Save GalindoSVQ/3830c35ba324aeacdd9e5f2c24d56c5e to your computer and use it in GitHub Desktop.
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 characters
| import * as React from 'react'; | |
| React.useEffectEvent = React.experimental_useEffectEvent; | |
| export function useCountdown(endTime, options) { | |
| const [count, setCount] = React.useState(null); | |
| const intervalIdRef = React.useRef(null); | |
| const handleClearInterval = () => { | |
| window.clearInterval(intervalIdRef.current); | |
| }; | |
| const onTick = React.useEffectEvent(() => { | |
| if (count === 0) { | |
| handleClearInterval(); | |
| options.onComplete(); | |
| } else { | |
| setCount(count - 1); | |
| options.onTick(); | |
| } | |
| }); | |
| React.useEffect(() => { | |
| setCount(Math.round((endTime - Date.now()) / options.interval)); | |
| }, [endTime, options.interval]); | |
| React.useEffect(() => { | |
| intervalIdRef.current = window.setInterval(onTick, options.interval); | |
| return () => handleClearInterval(); | |
| }, [options.interval]); | |
| return count; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackblitz.com/edit/stackblitz-starters-bkgnns