blob: df3cb63a278230719c8a020a464267b5e2c0c333 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import { useEffect, useState } from "react";
const useCountdown = (targetDate, update) => {
const countDownDate = new Date(targetDate).getTime();
const [countDown, setCountDown] = useState(
countDownDate - new Date().getTime()
);
useEffect(() => {
const interval = setInterval(() => {
const newCountDown = countDownDate - new Date().getTime();
setCountDown(newCountDown);
if (newCountDown <= 0 && newCountDown > -1000) {
update();
}
}, 1000);
return () => clearInterval(interval);
}, [countDownDate, update]);
return getReturnValues(countDown);
};
const getReturnValues = (countDown) => {
// calculate time left
const days = Math.floor(countDown / (1000 * 60 * 60 * 24));
const hours = Math.floor(
(countDown % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
);
const minutes = Math.floor((countDown % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((countDown % (1000 * 60)) / 1000);
return [days, hours, minutes, seconds];
};
export { useCountdown };
|