Chris@0: /** Chris@0: * @file Chris@0: * Adapted from underscore.js with the addition Drupal namespace. Chris@0: */ Chris@0: Chris@0: /** Chris@0: * Limits the invocations of a function in a given time frame. Chris@0: * Chris@0: * The debounce function wrapper should be used sparingly. One clear use case Chris@0: * is limiting the invocation of a callback attached to the window resize event. Chris@0: * Chris@0: * Before using the debounce function wrapper, consider first whether the Chris@0: * callback could be attached to an event that fires less frequently or if the Chris@0: * function can be written in such a way that it is only invoked under specific Chris@0: * conditions. Chris@0: * Chris@0: * @param {function} func Chris@0: * The function to be invoked. Chris@0: * @param {number} wait Chris@0: * The time period within which the callback function should only be Chris@0: * invoked once. For example if the wait period is 250ms, then the callback Chris@0: * will only be called at most 4 times per second. Chris@0: * @param {bool} immediate Chris@0: * Whether we wait at the beginning or end to execute the function. Chris@0: * Chris@0: * @return {function} Chris@0: * The debounced function. Chris@0: */ Chris@17: Drupal.debounce = function(func, wait, immediate) { Chris@0: let timeout; Chris@0: let result; Chris@17: return function(...args) { Chris@0: const context = this; Chris@17: const later = function() { Chris@0: timeout = null; Chris@0: if (!immediate) { Chris@0: result = func.apply(context, args); Chris@0: } Chris@0: }; Chris@0: const callNow = immediate && !timeout; Chris@0: clearTimeout(timeout); Chris@0: timeout = setTimeout(later, wait); Chris@0: if (callNow) { Chris@0: result = func.apply(context, args); Chris@0: } Chris@0: return result; Chris@0: }; Chris@0: };