All Downloads are FREE. Search and download functionalities are using the official Maven repository.

package.react-utils.useTimer.useTimer.js Maven / Gradle / Ivy

Go to download

A package encapsulating common code across neeto projects including initializers, utility functions, common components and hooks and so on.

There is a newer version: 4.12.3
Show newest version
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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy