package.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.
import { useRef, useSyncExternalStore } from "react";
import { isNotEmpty } from "@bigbinary/neeto-cist";
var subscriptions = [];
var interval = null;
var initiateInterval = function initiateInterval() {
// Create new interval if there are no subscriptions.
if (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 (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 = useRef(Date.now());
return useSyncExternalStore(subscribe, function () {
var now = Date.now();
var lastUpdated = lastUpdatedRef.current;
if (now - lastUpdated >= delay * 1000) lastUpdated = now;
lastUpdatedRef.current = lastUpdated;
return lastUpdated;
});
};
export default useTimer;
//# sourceMappingURL=useTimer.js.map