package.cjs.react-utils.useTimer.useTimer.js Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of neeto-commons-frontend Show documentation
Show all versions of neeto-commons-frontend Show documentation
A package encapsulating common code across neeto projects including initializers, utility functions, common components and hooks and so on.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = require("react");
var _neetoCist = require("@bigbinary/neeto-cist");
var subscriptions = [];
var interval = null;
var initiateInterval = function initiateInterval() {
// Create new interval if there are no subscriptions.
if ((0, _neetoCist.isNotEmpty)(subscriptions)) return;
interval = setInterval(function () {
subscriptions.forEach(function (callback) {
return callback();
});
}, 1000);
};
var cleanupInterval = function cleanupInterval() {
// Cleanup existing interval if there are no more subscriptions
if ((0, _neetoCist.isNotEmpty)(subscriptions)) return;
clearInterval(interval);
};
var subscribe = function subscribe(callback) {
initiateInterval();
subscriptions.push(callback);
return function () {
subscriptions.splice(subscriptions.indexOf(callback), 1);
cleanupInterval();
};
};
var useTimer = function useTimer() {
var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 60;
var lastUpdatedRef = (0, _react.useRef)(Date.now());
return (0, _react.useSyncExternalStore)(subscribe, function () {
var now = Date.now();
var lastUpdated = lastUpdatedRef.current;
if (now - lastUpdated >= delay * 1000) lastUpdated = now;
lastUpdatedRef.current = lastUpdated;
return lastUpdated;
});
};
var _default = useTimer;
exports["default"] = _default;
//# sourceMappingURL=useTimer.js.map