UNPKG

@wordpress/compose

Version:
68 lines (64 loc) 1.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _element = require("@wordpress/element"); var _createHigherOrderComponent = require("../../utils/create-higher-order-component"); var _jsxRuntime = require("react/jsx-runtime"); /** * WordPress dependencies */ /** * Internal dependencies */ /** * We cannot use the `Window['setTimeout']` and `Window['clearTimeout']` * types here because those functions include functionality that is not handled * by this component, like the ability to pass extra arguments. * * In the case of this component, we only handle the simplest case where * `setTimeout` only accepts a function (not a string) and an optional delay. */ /** * A higher-order component used to provide and manage delayed function calls * that ought to be bound to a component's lifecycle. */ const withSafeTimeout = (0, _createHigherOrderComponent.createHigherOrderComponent)(OriginalComponent => { return class WrappedComponent extends _element.Component { constructor(props) { super(props); this.timeouts = []; this.setTimeout = this.setTimeout.bind(this); this.clearTimeout = this.clearTimeout.bind(this); } componentWillUnmount() { this.timeouts.forEach(clearTimeout); } setTimeout(fn, delay) { const id = setTimeout(() => { fn(); this.clearTimeout(id); }, delay); this.timeouts.push(id); return id; } clearTimeout(id) { clearTimeout(id); this.timeouts = this.timeouts.filter(timeoutId => timeoutId !== id); } render() { return ( /*#__PURE__*/ // @ts-ignore (0, _jsxRuntime.jsx)(OriginalComponent, { ...this.props, setTimeout: this.setTimeout, clearTimeout: this.clearTimeout }) ); } }; }, 'withSafeTimeout'); var _default = exports.default = withSafeTimeout; //# sourceMappingURL=index.js.map