events_resize.js

import debounce from './debounce';

/**
 * @module resize
 * @description Bind a function to the resize event on window with an automatic default delay.
 *
 * @since 1.0.0
 *
 * @param {Function} fn   The function to run on resize.
 * @param {number}   wait The delay for the debouncing of the resize event.
 * @param {boolean}  add  Whether to add or remove the listener.
 *
 * @requires debounce
 *
 * @return {void}
 *
 * @example
 * import { resize } from "@gravityforms/utils";
 *
 * function Example() {
 *     // do something on resize
 * };
 *
 * resize( Example, 400 );
 *
 */
export default function resize( fn = () => {}, wait = 200, add = true ) {
	if ( add ) {
		window.addEventListener( 'resize', debounce( fn, { wait } ) );
	} else {
		window.removeEventListener( 'resize', debounce( fn, { wait } ) );
	}
}