@atlaskit/motion
Version:
A set of utilities to apply motion in your application.
44 lines (42 loc) • 1.53 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useSetTimeout = void 0;
var _react = require("react");
var _getHookDeps = require("./get-hook-deps");
// Handle both browser and Node.js environments
/**
* Will return set timeout as a function which will clean itself up.
*/
// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
var useSetTimeout = exports.useSetTimeout = function useSetTimeout() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
cleanup: 'unmount'
};
var timeouts = (0, _react.useRef)([]);
(0, _react.useEffect)(function () {
return function () {
if (timeouts.current.length) {
timeouts.current.forEach(function (id) {
return clearTimeout(id);
});
timeouts.current = [];
}
};
// We dynamically set this so we either clean up on the next effect - or on unmount.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, (0, _getHookDeps.getHookDeps)(opts));
return (0, _react.useCallback)(function (handler, timeout) {
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
var id = setTimeout.apply(void 0, [function () {
timeouts.current = timeouts.current.filter(function (timeoutId) {
return timeoutId !== id;
});
handler();
}, timeout].concat(args));
timeouts.current.push(id);
}, []);
};