Created
July 15, 2022 04:41
-
-
Save permpkin/42ebc9a80c5ca28d91719364da2555e8 to your computer and use it in GitHub Desktop.
simple react countdown component with callback
This file contains 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 { useEffect, useState } from "react"; | |
interface Props { | |
from: number | |
callback: Function | |
} | |
export const CountDown = ({ from, callback }:Props) => { | |
const [time, setTime] = useState(from) | |
let timer: NodeJS.Timeout; | |
const iterate = () => { | |
setTime(time - 1) | |
if (time > 0) { | |
timer = setTimeout(iterate, 1000) | |
} else { | |
callback() | |
} | |
} | |
useEffect(() => { | |
if (timer) clearTimeout(timer) | |
if (time > 0) { | |
timer = setTimeout(iterate, 1000) | |
} else { | |
callback() | |
} | |
return () => clearTimeout(timer); | |
}, [time]); | |
return ( | |
<span>{`${time}s`}</span> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment