Skip to content

Instantly share code, notes, and snippets.

@GalindoSVQ
Created January 11, 2024 21:07
Show Gist options
  • Save GalindoSVQ/3830c35ba324aeacdd9e5f2c24d56c5e to your computer and use it in GitHub Desktop.
Save GalindoSVQ/3830c35ba324aeacdd9e5f2c24d56c5e to your computer and use it in GitHub Desktop.
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;
}
@GalindoSVQ
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment