ls-deno/islands/Countdown.tsx

28 lines
723 B
TypeScript
Raw Normal View History

2022-09-27 14:41:17 -05:00
import { useEffect, useState } from "preact/hooks";
const timeFmt = new Intl.RelativeTimeFormat("en-US");
export default function Countdown(props: { target: string }) {
const target = new Date(props.target);
const [now, setNow] = useState(new Date());
useEffect(() => {
const timer = setInterval(() => {
setNow((now) => {
if (now > target) {
clearInterval(timer);
}
return new Date();
});
}, 1000);
return () => clearInterval(timer);
}, [props.target]);
if (now > target) {
return <span>🎉</span>;
}
const secondsLeft = Math.ceil((target.getTime() - now.getTime()) / 1000);
return <span>{timeFmt.format(secondsLeft, "seconds")}</span>;
}