1// noinspection ES6ConvertVarToLetConst 2window.combos = (function (module){ 3 4 /** 5 * 6 * @param callBack - the function to debounce 7 * @param interval - in ms 8 * @param leadingExecution - if true, the execution happens before the interval 9 * @returns {(function(): void)|*} 10 */ 11 module.debounce = function (callBack, interval, leadingExecution = false) { 12 13 // the schedule identifier, if it's not null/undefined, a callBack function was scheduled 14 let timerId; 15 16 return function () { 17 18 // Does the previous run has schedule a run 19 let wasFunctionScheduled = (typeof timerId === 'number'); 20 21 // Delete the previous run (if timerId is null, it does nothing) 22 clearTimeout(timerId); 23 24 // Capture the environment (this and argument) and wraps the callback function 25 let funcToDebounceThis = this, funcToDebounceArgs = arguments; 26 let funcToSchedule = function () { 27 28 // Reset/delete the schedule 29 clearTimeout(timerId); 30 timerId = null; 31 32 // trailing execution happens at the end of the interval 33 if (!leadingExecution) { 34 // Call the original function with apply 35 callBack.apply(funcToDebounceThis, funcToDebounceArgs); 36 } 37 38 } 39 40 // Schedule a new execution at each execution 41 timerId = setTimeout(funcToSchedule, interval); 42 43 // Leading execution 44 if (!wasFunctionScheduled && leadingExecution) callBack.apply(funcToDebounceThis, funcToDebounceArgs); 45 46 } 47 48 } 49 50 return module; 51}(window.combos || {})); 52 53 54 55