bdd-use-countdown
Version:
React hook encapsulating countdown functionality
61 lines (60 loc) • 1.61 kB
JavaScript
// src/index.ts
import { useEffect, useState, useRef } from "react";
import { DateX } from "bdd-date-ext";
function useCountdown({
start = new DateX(),
end,
onStart,
onEnd,
timedActions = []
}) {
const [values, setValues] = useState(
() => diffTime(start, end)
);
const timerRef = useRef(null);
const executedActionsRef = useRef(/* @__PURE__ */ new Set());
useEffect(() => {
onStart?.(start);
timerRef.current = setInterval(() => {
const now = new DateX();
const timeLeft = diffTime(now, end);
setValues(timeLeft);
for (const { timestamp, action } of timedActions) {
const ts = timestamp.getTime();
if (now.getTime() >= ts && !executedActionsRef.current.has(ts)) {
action(timestamp);
executedActionsRef.current.add(ts);
}
}
if (now.getTime() >= end.getTime()) {
clearInterval(timerRef.current);
onEnd?.(end);
}
}, 1e3);
return () => clearInterval(timerRef.current);
}, [end.getTime()]);
return values;
}
function diffTime(from, to) {
const durationMs = Math.max(to.getTime() - from.getTime(), 0);
let remaining = durationMs;
const ms = remaining % 1e3;
remaining = Math.floor(remaining / 1e3);
const s = remaining % 60;
remaining = Math.floor(remaining / 60);
const m = remaining % 60;
remaining = Math.floor(remaining / 60);
const h = remaining % 24;
remaining = Math.floor(remaining / 24);
const d = remaining;
return {
days: d,
hours: h,
minutes: m,
seconds: s,
milliseconds: ms
};
}
export {
useCountdown
};