UNPKG

@wordpress/compose

Version:
64 lines (55 loc) 1.6 kB
import _extends from "@babel/runtime/helpers/esm/extends"; import { createElement } from "@wordpress/element"; /** * External dependencies */ import { without } from 'lodash'; /** * WordPress dependencies */ import { Component } from '@wordpress/element'; /** * Internal dependencies */ import createHigherOrderComponent from '../../utils/create-higher-order-component'; /** * A higher-order component used to provide and manage delayed function calls * that ought to be bound to a component's lifecycle. * * @param {WPComponent} OriginalComponent Component requiring setTimeout * * @return {WPComponent} Wrapped component. */ const withSafeTimeout = createHigherOrderComponent(OriginalComponent => { return class WrappedComponent extends Component { constructor() { super(...arguments); 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 = without(this.timeouts, id); } render() { return createElement(OriginalComponent, _extends({}, this.props, { setTimeout: this.setTimeout, clearTimeout: this.clearTimeout })); } }; }, 'withSafeTimeout'); export default withSafeTimeout; //# sourceMappingURL=index.js.map