react-countdown-typescript
Version:
An utilities of countdown for React with full rich-features.
99 lines (85 loc) • 3.02 kB
JavaScript
Object.defineProperty(exports, '__esModule', { value: true });
var react = require('react');
var useCountdown = function useCountdown(timeToCount, interval) {
if (timeToCount === void 0) {
timeToCount = 60000;
}
if (interval === void 0) {
interval = 1000;
}
var defaultCountdown = {
requestId: undefined,
started: undefined,
lastInterval: undefined,
timeLeft: 0,
timeToCount: timeToCount
};
var _useState = react.useState(timeToCount),
timeLeft = _useState[0],
setTimeLeft = _useState[1];
var timer = react.useRef(defaultCountdown);
var run = function run(ts) {
if (!timer.current.started) {
timer.current.started = ts;
timer.current.lastInterval = ts;
}
var localInterval = Math.min(interval, timer.current.timeLeft || Number.POSITIVE_INFINITY);
if (ts - timer.current.lastInterval >= localInterval) {
timer.current.lastInterval += localInterval;
setTimeLeft(function (timeLeft) {
return timer.current.timeLeft = timeLeft - localInterval;
});
}
if (ts - timer.current.started < timer.current.timeToCount) {
timer.current.requestId = window.requestAnimationFrame(run);
} else {
timer.current = defaultCountdown;
setTimeLeft(0);
}
};
var start = react.useCallback(function (newTimeToCount) {
if (timer.current.requestId) window.cancelAnimationFrame(timer.current.requestId);
var ttc = newTimeToCount !== undefined ? newTimeToCount : timeToCount;
timer.current.started = undefined;
timer.current.lastInterval = undefined;
timer.current.timeToCount = ttc;
timer.current.requestId = window.requestAnimationFrame(run);
setTimeLeft(ttc);
}, []);
var pause = react.useCallback(function () {
if (timer.current.requestId) window.cancelAnimationFrame(timer.current.requestId);
timer.current.started = undefined;
timer.current.lastInterval = undefined;
timer.current.timeToCount = timer.current.timeLeft;
}, []);
var resume = react.useCallback(function () {
if (!timer.current.started && timer.current.timeLeft > 0) {
if (timer.current.requestId) window.cancelAnimationFrame(timer.current.requestId);
timer.current.requestId = window.requestAnimationFrame(run);
}
}, []);
var reset = react.useCallback(function () {
if (timer.current.timeLeft) {
if (timer.current.requestId) window.cancelAnimationFrame(timer.current.requestId);
timer.current = defaultCountdown;
setTimeLeft(0);
}
}, []);
var actions = react.useMemo(function () {
return {
start: start,
pause: pause,
resume: resume,
reset: reset
};
}, []);
react.useEffect(function () {
return function () {
if (timer.current.requestId) window.cancelAnimationFrame(timer.current.requestId);
};
}, []);
return [timeLeft, actions];
};
exports.useCountdown = useCountdown;
//# sourceMappingURL=react-countdown-typescript.cjs.development.js.map
;