/* eslint-disable */
/**
* @module delay
* @description A chainable function for delaying execution of a function or group of functions.
*
* @since 1.0.0
*
* @param {Function} fn Function to execute.
* @param {number} t Delay time in milliseconds.
*
* @return {Function} Returns the a function that can then be chained with another call.
*
* @example
* import { delay } from "@gravityforms/utils";
*
* function Example() {
* delay(fn1, 400).delay(fn2, 500);
* }
*
* function fn1() {
* console.log( 'fn1: ' + Date.now() );
* }
* function fn2() {
* console.log( 'fn2: ' + Date.now() );
* }
*
*/
export default function( fn = () => {}, t = 100 ) {
let queue = [];
let self;
let timer;
/**
*
* @param fn
* @param t
*/
function schedule( fn, t ) {
timer = window.setTimeout( function() {
timer = null;
fn();
if ( queue.length ) {
const item = queue.shift();
schedule( item.fn, item.t );
}
}, t );
}
self = {
delay( fn, t ) {
// if already queuing things or running a timer,
// then just add to the queue
if ( queue.length || timer ) {
queue.push( { fn, t } );
} else {
// no queue or timer yet, so schedule the timer
schedule( fn, t );
}
return self;
},
cancel() {
window.clearTimeout( timer );
queue = [];
return self;
},
};
return self.delay( fn, t );
}