annotate core/misc/debounce.es6.js @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents 129ea1e6d783
children
rev   line source
Chris@0 1 /**
Chris@0 2 * @file
Chris@0 3 * Adapted from underscore.js with the addition Drupal namespace.
Chris@0 4 */
Chris@0 5
Chris@0 6 /**
Chris@0 7 * Limits the invocations of a function in a given time frame.
Chris@0 8 *
Chris@0 9 * The debounce function wrapper should be used sparingly. One clear use case
Chris@0 10 * is limiting the invocation of a callback attached to the window resize event.
Chris@0 11 *
Chris@0 12 * Before using the debounce function wrapper, consider first whether the
Chris@0 13 * callback could be attached to an event that fires less frequently or if the
Chris@0 14 * function can be written in such a way that it is only invoked under specific
Chris@0 15 * conditions.
Chris@0 16 *
Chris@0 17 * @param {function} func
Chris@0 18 * The function to be invoked.
Chris@0 19 * @param {number} wait
Chris@0 20 * The time period within which the callback function should only be
Chris@0 21 * invoked once. For example if the wait period is 250ms, then the callback
Chris@0 22 * will only be called at most 4 times per second.
Chris@0 23 * @param {bool} immediate
Chris@0 24 * Whether we wait at the beginning or end to execute the function.
Chris@0 25 *
Chris@0 26 * @return {function}
Chris@0 27 * The debounced function.
Chris@0 28 */
Chris@17 29 Drupal.debounce = function(func, wait, immediate) {
Chris@0 30 let timeout;
Chris@0 31 let result;
Chris@17 32 return function(...args) {
Chris@0 33 const context = this;
Chris@17 34 const later = function() {
Chris@0 35 timeout = null;
Chris@0 36 if (!immediate) {
Chris@0 37 result = func.apply(context, args);
Chris@0 38 }
Chris@0 39 };
Chris@0 40 const callNow = immediate && !timeout;
Chris@0 41 clearTimeout(timeout);
Chris@0 42 timeout = setTimeout(later, wait);
Chris@0 43 if (callNow) {
Chris@0 44 result = func.apply(context, args);
Chris@0 45 }
Chris@0 46 return result;
Chris@0 47 };
Chris@0 48 };