UNPKG

@barelyreaper/background-timer

Version:

Simple react hook to run a timer in the background

45 lines (44 loc) 1.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useBackgroundTimer = void 0; const react_1 = require("react"); const useBackgroundTimer = (timeInMilliseconds, options = {}) => { const [timer, setTimer] = react_1.useState(); const [endTime, setEndTime] = react_1.useState(); const timerRef = react_1.useRef(); react_1.useEffect(() => { if (!endTime && timeInMilliseconds > 0) { setEndTime(_getEndTime()); setTimer(timeInMilliseconds); } }, [timeInMilliseconds]); react_1.useEffect(() => { function tick() { const now = new Date().getTime(); const diff = endTime - now; if (diff <= 0) { clearInterval(timerRef.current); options?.onTimerEnd && options.onTimerEnd(); setTimer(0); } else { setTimer(diff); } } if (timer > 0) { timerRef.current = setInterval(tick, 1000); return () => clearInterval(timerRef.current); } return () => { }; }, [timer]); function reset() { clearInterval(timerRef.current); setEndTime(_getEndTime()); setTimer(timeInMilliseconds); } function _getEndTime() { return new Date().setTime(new Date().getTime() + timeInMilliseconds); } return { timer, reset }; }; exports.useBackgroundTimer = useBackgroundTimer;