debouncer.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // Copyright 2015 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Definition of the goog.async.Debouncer class.
  16. *
  17. * @see ../demos/timers.html
  18. */
  19. goog.provide('goog.async.Debouncer');
  20. goog.require('goog.Disposable');
  21. goog.require('goog.Timer');
  22. /**
  23. * Debouncer will perform a specified action exactly once for any sequence of
  24. * signals fired repeatedly so long as they are fired less than a specified
  25. * interval apart (in milliseconds). Whether it receives one signal or multiple,
  26. * it will always wait until a full interval has elapsed since the last signal
  27. * before performing the action.
  28. * @param {function(this: T, ...?)} listener Function to callback when the
  29. * action is triggered.
  30. * @param {number} interval Interval over which to debounce. The listener will
  31. * only be called after the full interval has elapsed since the last signal.
  32. * @param {T=} opt_handler Object in whose scope to call the listener.
  33. * @constructor
  34. * @struct
  35. * @extends {goog.Disposable}
  36. * @final
  37. * @template T
  38. */
  39. goog.async.Debouncer = function(listener, interval, opt_handler) {
  40. goog.async.Debouncer.base(this, 'constructor');
  41. /**
  42. * Function to callback
  43. * @const @private {function(this: T, ...?)}
  44. */
  45. this.listener_ =
  46. opt_handler != null ? goog.bind(listener, opt_handler) : listener;
  47. /**
  48. * Interval for the debounce time
  49. * @const @private {number}
  50. */
  51. this.interval_ = interval;
  52. /**
  53. * Cached callback function invoked after the debounce timeout completes
  54. * @const @private {!Function}
  55. */
  56. this.callback_ = goog.bind(this.onTimer_, this);
  57. /**
  58. * Indicates that the action is pending and needs to be fired.
  59. * @private {boolean}
  60. */
  61. this.shouldFire_ = false;
  62. /**
  63. * Indicates the count of nested pauses currently in effect on the debouncer.
  64. * When this count is not zero, fired actions will be postponed until the
  65. * debouncer is resumed enough times to drop the pause count to zero.
  66. * @private {number}
  67. */
  68. this.pauseCount_ = 0;
  69. /**
  70. * Timer for scheduling the next callback
  71. * @private {?number}
  72. */
  73. this.timer_ = null;
  74. /**
  75. * When set this is a timestamp. On the onfire we want to reschedule the
  76. * callback so it ends up at this time.
  77. * @private {?number}
  78. */
  79. this.refireAt_ = null;
  80. /**
  81. * The last arguments passed into {@code fire}.
  82. * @private {!IArrayLike}
  83. */
  84. this.args_ = [];
  85. };
  86. goog.inherits(goog.async.Debouncer, goog.Disposable);
  87. /**
  88. * Notifies the debouncer that the action has happened. It will debounce the
  89. * call so that the callback is only called after the last action in a sequence
  90. * of actions separated by periods less the interval parameter passed to the
  91. * constructor, passing the arguments from the last call of this function into
  92. * the debounced function.
  93. * @param {...?} var_args Arguments to pass on to the debounced function.
  94. */
  95. goog.async.Debouncer.prototype.fire = function(var_args) {
  96. this.args_ = arguments;
  97. // When this method is called, we need to prevent fire() calls from within the
  98. // previous interval from calling the callback. The simplest way of doing this
  99. // is to call this.stop() which calls clearTimeout, and then reschedule the
  100. // timeout. However clearTimeout and setTimeout are expensive, so we just
  101. // leave them untouched and when they do happen we potentially reschedule.
  102. this.shouldFire_ = false;
  103. if (this.timer_) {
  104. this.refireAt_ = goog.now() + this.interval_;
  105. return;
  106. }
  107. this.timer_ = goog.Timer.callOnce(this.callback_, this.interval_);
  108. };
  109. /**
  110. * Cancels any pending action callback. The debouncer can be restarted by
  111. * calling {@link #fire}.
  112. */
  113. goog.async.Debouncer.prototype.stop = function() {
  114. if (this.timer_) {
  115. goog.Timer.clear(this.timer_);
  116. this.timer_ = null;
  117. }
  118. this.refireAt_ = null;
  119. this.shouldFire_ = false;
  120. this.args_ = [];
  121. };
  122. /**
  123. * Pauses the debouncer. All pending and future action callbacks will be delayed
  124. * until the debouncer is resumed. Pauses can be nested.
  125. */
  126. goog.async.Debouncer.prototype.pause = function() {
  127. ++this.pauseCount_;
  128. };
  129. /**
  130. * Resumes the debouncer. If doing so drops the pausing count to zero, pending
  131. * action callbacks will be executed as soon as possible, but still no sooner
  132. * than an interval's delay after the previous call. Future action callbacks
  133. * will be executed as normal.
  134. */
  135. goog.async.Debouncer.prototype.resume = function() {
  136. if (!this.pauseCount_) {
  137. return;
  138. }
  139. --this.pauseCount_;
  140. if (!this.pauseCount_ && this.shouldFire_) {
  141. this.doAction_();
  142. }
  143. };
  144. /** @override */
  145. goog.async.Debouncer.prototype.disposeInternal = function() {
  146. this.stop();
  147. goog.async.Debouncer.base(this, 'disposeInternal');
  148. };
  149. /**
  150. * Handler for the timer to fire the debouncer.
  151. * @private
  152. */
  153. goog.async.Debouncer.prototype.onTimer_ = function() {
  154. // There is a newer call to fire() within the debounce interval.
  155. // Reschedule the callback and return.
  156. if (this.refireAt_) {
  157. this.timer_ =
  158. goog.Timer.callOnce(this.callback_, this.refireAt_ - goog.now());
  159. this.refireAt_ = null;
  160. return;
  161. }
  162. this.timer_ = null;
  163. if (!this.pauseCount_) {
  164. this.doAction_();
  165. } else {
  166. this.shouldFire_ = true;
  167. }
  168. };
  169. /**
  170. * Calls the callback.
  171. * @private
  172. */
  173. goog.async.Debouncer.prototype.doAction_ = function() {
  174. this.shouldFire_ = false;
  175. this.listener_.apply(null, this.args_);
  176. };