Skip to content

Instantly share code, notes, and snippets.

@ibelick
Created March 24, 2022 08:43
Show Gist options
  • Save ibelick/4f26adabf9d87803b0c8432cc1ed9b82 to your computer and use it in GitHub Desktop.
Save ibelick/4f26adabf9d87803b0c8432cc1ed9b82 to your computer and use it in GitHub Desktop.
Basic Timer in React
import React, { useEffect, useState } from "react";
import { dynamicTimeLeft } from "utils/date";
interface TimerProps {
dateEnd: Date;
}
const Timer: React.FC<TimerProps> = ({ dateEnd }) => {
const [time, setTime] = useState<null | string>(null);
useEffect(() => {
if (!dateEnd) {
return;
}
const intervalId = setInterval(function () {
const now = new Date();
const remainingTime = dynamicTimeLeft(now, dateEnd);
setTime(remainingTime);
}, 1000);
return () => {
clearInterval(intervalId);
};
}, [dateEnd]);
return <span className="text-xl font-medium">{time}</span>;
};
const dynamicTimeLeft = (date1: Date, date2: Date) => {
const distance = date2.getTime() - date1.getTime();
const hours = Math.floor(
(distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
);
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
const addZero = (t: number) => (t > 9 ? t : `0${t}`);
return `${addZero(hours)}:${addZero(minutes)}:${addZero(seconds)}`;
};
export default Timer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment