Skip to content

Instantly share code, notes, and snippets.

@permpkin
Created July 15, 2022 04:41
Show Gist options
  • Save permpkin/42ebc9a80c5ca28d91719364da2555e8 to your computer and use it in GitHub Desktop.
Save permpkin/42ebc9a80c5ca28d91719364da2555e8 to your computer and use it in GitHub Desktop.
simple react countdown component with callback
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