Skip to content

Instantly share code, notes, and snippets.

@javierd79
Created March 27, 2023 05:50
Show Gist options
  • Save javierd79/6a7b25ff48a22d212944ee9fbb080172 to your computer and use it in GitHub Desktop.
Save javierd79/6a7b25ff48a22d212944ee9fbb080172 to your computer and use it in GitHub Desktop.
useTimer hook to handle timer from Now to a end time.
import { useState, useEffect } from 'react';
import moment from 'moment';
type TimerHook = {
time: string;
stop: () => void;
};
const useTimer = (endTime: string): TimerHook => {
const duration = moment.duration(moment(endTime, 'HH:mm:ss').diff(moment(moment().format('HH:mm:ss'), 'HH:mm:ss')));
const [time, setTime] = useState(duration.asSeconds());
const [intervalId, setIntervalId] = useState<NodeJS.Timeout | null>(null);
const stop = () => {
if (intervalId) {
clearInterval(intervalId);
setIntervalId(null);
}
};
useEffect(() => {
const id = setInterval(() => {
setTime((prevTime) => {
const nextTime = prevTime - 0.5;
if (nextTime === 0) clearInterval(id);
return nextTime;
});
}, 1000);
setIntervalId(id);
return () => {
if (intervalId) clearInterval(intervalId);
};
}, []);
const formattedTime = moment.utc(time * 1000).format('HH:mm:ss');
return { time: formattedTime, stop };
};
export default useTimer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment