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

package.cjs.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
"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 = exports["default"] = useTimer;
//# sourceMappingURL=useTimer.js.map




© 2015 - 2024 Weber Informatics LLC | Privacy Policy