Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

debounce.js 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. var isObject = require('./isObject'),
  2. now = require('./now'),
  3. toNumber = require('./toNumber');
  4. /** Error message constants. */
  5. var FUNC_ERROR_TEXT = 'Expected a function';
  6. /* Built-in method references for those with the same name as other `lodash` methods. */
  7. var nativeMax = Math.max,
  8. nativeMin = Math.min;
  9. /**
  10. * Creates a debounced function that delays invoking `func` until after `wait`
  11. * milliseconds have elapsed since the last time the debounced function was
  12. * invoked. The debounced function comes with a `cancel` method to cancel
  13. * delayed `func` invocations and a `flush` method to immediately invoke them.
  14. * Provide `options` to indicate whether `func` should be invoked on the
  15. * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
  16. * with the last arguments provided to the debounced function. Subsequent
  17. * calls to the debounced function return the result of the last `func`
  18. * invocation.
  19. *
  20. * **Note:** If `leading` and `trailing` options are `true`, `func` is
  21. * invoked on the trailing edge of the timeout only if the debounced function
  22. * is invoked more than once during the `wait` timeout.
  23. *
  24. * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
  25. * until to the next tick, similar to `setTimeout` with a timeout of `0`.
  26. *
  27. * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
  28. * for details over the differences between `_.debounce` and `_.throttle`.
  29. *
  30. * @static
  31. * @memberOf _
  32. * @since 0.1.0
  33. * @category Function
  34. * @param {Function} func The function to debounce.
  35. * @param {number} [wait=0] The number of milliseconds to delay.
  36. * @param {Object} [options={}] The options object.
  37. * @param {boolean} [options.leading=false]
  38. * Specify invoking on the leading edge of the timeout.
  39. * @param {number} [options.maxWait]
  40. * The maximum time `func` is allowed to be delayed before it's invoked.
  41. * @param {boolean} [options.trailing=true]
  42. * Specify invoking on the trailing edge of the timeout.
  43. * @returns {Function} Returns the new debounced function.
  44. * @example
  45. *
  46. * // Avoid costly calculations while the window size is in flux.
  47. * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
  48. *
  49. * // Invoke `sendMail` when clicked, debouncing subsequent calls.
  50. * jQuery(element).on('click', _.debounce(sendMail, 300, {
  51. * 'leading': true,
  52. * 'trailing': false
  53. * }));
  54. *
  55. * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
  56. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
  57. * var source = new EventSource('/stream');
  58. * jQuery(source).on('message', debounced);
  59. *
  60. * // Cancel the trailing debounced invocation.
  61. * jQuery(window).on('popstate', debounced.cancel);
  62. */
  63. function debounce(func, wait, options) {
  64. var lastArgs,
  65. lastThis,
  66. maxWait,
  67. result,
  68. timerId,
  69. lastCallTime,
  70. lastInvokeTime = 0,
  71. leading = false,
  72. maxing = false,
  73. trailing = true;
  74. if (typeof func != 'function') {
  75. throw new TypeError(FUNC_ERROR_TEXT);
  76. }
  77. wait = toNumber(wait) || 0;
  78. if (isObject(options)) {
  79. leading = !!options.leading;
  80. maxing = 'maxWait' in options;
  81. maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
  82. trailing = 'trailing' in options ? !!options.trailing : trailing;
  83. }
  84. function invokeFunc(time) {
  85. var args = lastArgs,
  86. thisArg = lastThis;
  87. lastArgs = lastThis = undefined;
  88. lastInvokeTime = time;
  89. result = func.apply(thisArg, args);
  90. return result;
  91. }
  92. function leadingEdge(time) {
  93. // Reset any `maxWait` timer.
  94. lastInvokeTime = time;
  95. // Start the timer for the trailing edge.
  96. timerId = setTimeout(timerExpired, wait);
  97. // Invoke the leading edge.
  98. return leading ? invokeFunc(time) : result;
  99. }
  100. function remainingWait(time) {
  101. var timeSinceLastCall = time - lastCallTime,
  102. timeSinceLastInvoke = time - lastInvokeTime,
  103. timeWaiting = wait - timeSinceLastCall;
  104. return maxing
  105. ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
  106. : timeWaiting;
  107. }
  108. function shouldInvoke(time) {
  109. var timeSinceLastCall = time - lastCallTime,
  110. timeSinceLastInvoke = time - lastInvokeTime;
  111. // Either this is the first call, activity has stopped and we're at the
  112. // trailing edge, the system time has gone backwards and we're treating
  113. // it as the trailing edge, or we've hit the `maxWait` limit.
  114. return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
  115. (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
  116. }
  117. function timerExpired() {
  118. var time = now();
  119. if (shouldInvoke(time)) {
  120. return trailingEdge(time);
  121. }
  122. // Restart the timer.
  123. timerId = setTimeout(timerExpired, remainingWait(time));
  124. }
  125. function trailingEdge(time) {
  126. timerId = undefined;
  127. // Only invoke if we have `lastArgs` which means `func` has been
  128. // debounced at least once.
  129. if (trailing && lastArgs) {
  130. return invokeFunc(time);
  131. }
  132. lastArgs = lastThis = undefined;
  133. return result;
  134. }
  135. function cancel() {
  136. if (timerId !== undefined) {
  137. clearTimeout(timerId);
  138. }
  139. lastInvokeTime = 0;
  140. lastArgs = lastCallTime = lastThis = timerId = undefined;
  141. }
  142. function flush() {
  143. return timerId === undefined ? result : trailingEdge(now());
  144. }
  145. function debounced() {
  146. var time = now(),
  147. isInvoking = shouldInvoke(time);
  148. lastArgs = arguments;
  149. lastThis = this;
  150. lastCallTime = time;
  151. if (isInvoking) {
  152. if (timerId === undefined) {
  153. return leadingEdge(lastCallTime);
  154. }
  155. if (maxing) {
  156. // Handle invocations in a tight loop.
  157. clearTimeout(timerId);
  158. timerId = setTimeout(timerExpired, wait);
  159. return invokeFunc(lastCallTime);
  160. }
  161. }
  162. if (timerId === undefined) {
  163. timerId = setTimeout(timerExpired, wait);
  164. }
  165. return result;
  166. }
  167. debounced.cancel = cancel;
  168. debounced.flush = flush;
  169. return debounced;
  170. }
  171. module.exports = debounce;