conditionaldelay.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. // Copyright 2008 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 Defines a class useful for handling functions that must be
  16. * invoked later when some condition holds. Examples include deferred function
  17. * calls that return a boolean flag whether it succedeed or not.
  18. *
  19. * Example:
  20. *
  21. * function deferred() {
  22. * var succeeded = false;
  23. * // ... custom code
  24. * return succeeded;
  25. * }
  26. *
  27. * var deferredCall = new goog.async.ConditionalDelay(deferred);
  28. * deferredCall.onSuccess = function() {
  29. * alert('Success: The deferred function has been successfully executed.');
  30. * }
  31. * deferredCall.onFailure = function() {
  32. * alert('Failure: Time limit exceeded.');
  33. * }
  34. *
  35. * // Call the deferred() every 100 msec until it returns true,
  36. * // or 5 seconds pass.
  37. * deferredCall.start(100, 5000);
  38. *
  39. * // Stop the deferred function call (does nothing if it's not active).
  40. * deferredCall.stop();
  41. *
  42. */
  43. goog.provide('goog.async.ConditionalDelay');
  44. goog.require('goog.Disposable');
  45. goog.require('goog.async.Delay');
  46. /**
  47. * A ConditionalDelay object invokes the associated function after a specified
  48. * interval delay and checks its return value. If the function returns
  49. * {@code true} the conditional delay is cancelled and {@see #onSuccess}
  50. * is called. Otherwise this object keeps to invoke the deferred function until
  51. * either it returns {@code true} or the timeout is exceeded. In the latter case
  52. * the {@see #onFailure} method will be called.
  53. *
  54. * The interval duration and timeout can be specified each time the delay is
  55. * started. Calling start on an active delay will reset the timer.
  56. *
  57. * @param {function():boolean} listener Function to call when the delay
  58. * completes. Should return a value that type-converts to {@code true} if
  59. * the call succeeded and this delay should be stopped.
  60. * @param {Object=} opt_handler The object scope to invoke the function in.
  61. * @constructor
  62. * @struct
  63. * @extends {goog.Disposable}
  64. */
  65. goog.async.ConditionalDelay = function(listener, opt_handler) {
  66. goog.async.ConditionalDelay.base(this, 'constructor');
  67. /**
  68. * The delay interval in milliseconds to between the calls to the callback.
  69. * Note, that the callback may be invoked earlier than this interval if the
  70. * timeout is exceeded.
  71. * @private {number}
  72. */
  73. this.interval_ = 0;
  74. /**
  75. * The timeout timestamp until which the delay is to be executed.
  76. * A negative value means no timeout.
  77. * @private {number}
  78. */
  79. this.runUntil_ = 0;
  80. /**
  81. * True if the listener has been executed, and it returned {@code true}.
  82. * @private {boolean}
  83. */
  84. this.isDone_ = false;
  85. /**
  86. * The function that will be invoked after a delay.
  87. * @private {function():boolean}
  88. */
  89. this.listener_ = listener;
  90. /**
  91. * The object context to invoke the callback in.
  92. * @private {Object|undefined}
  93. */
  94. this.handler_ = opt_handler;
  95. /**
  96. * The underlying goog.async.Delay delegate object.
  97. * @private {goog.async.Delay}
  98. */
  99. this.delay_ = new goog.async.Delay(
  100. goog.bind(this.onTick_, this), 0 /*interval*/, this /*scope*/);
  101. };
  102. goog.inherits(goog.async.ConditionalDelay, goog.Disposable);
  103. /** @override */
  104. goog.async.ConditionalDelay.prototype.disposeInternal = function() {
  105. this.delay_.dispose();
  106. delete this.listener_;
  107. delete this.handler_;
  108. goog.async.ConditionalDelay.superClass_.disposeInternal.call(this);
  109. };
  110. /**
  111. * Starts the delay timer. The provided listener function will be called
  112. * repeatedly after the specified interval until the function returns
  113. * {@code true} or the timeout is exceeded. Calling start on an active timer
  114. * will stop the timer first.
  115. * @param {number=} opt_interval The time interval between the function
  116. * invocations (in milliseconds). Default is 0.
  117. * @param {number=} opt_timeout The timeout interval (in milliseconds). Takes
  118. * precedence over the {@code opt_interval}, i.e. if the timeout is less
  119. * than the invocation interval, the function will be called when the
  120. * timeout is exceeded. A negative value means no timeout. Default is 0.
  121. */
  122. goog.async.ConditionalDelay.prototype.start = function(
  123. opt_interval, opt_timeout) {
  124. this.stop();
  125. this.isDone_ = false;
  126. var timeout = opt_timeout || 0;
  127. this.interval_ = Math.max(opt_interval || 0, 0);
  128. this.runUntil_ = timeout < 0 ? -1 : (goog.now() + timeout);
  129. this.delay_.start(
  130. timeout < 0 ? this.interval_ : Math.min(this.interval_, timeout));
  131. };
  132. /**
  133. * Stops the delay timer if it is active. No action is taken if the timer is not
  134. * in use.
  135. */
  136. goog.async.ConditionalDelay.prototype.stop = function() {
  137. this.delay_.stop();
  138. };
  139. /**
  140. * @return {boolean} True if the delay is currently active, false otherwise.
  141. */
  142. goog.async.ConditionalDelay.prototype.isActive = function() {
  143. return this.delay_.isActive();
  144. };
  145. /**
  146. * @return {boolean} True if the listener has been executed and returned
  147. * {@code true} since the last call to {@see #start}.
  148. */
  149. goog.async.ConditionalDelay.prototype.isDone = function() {
  150. return this.isDone_;
  151. };
  152. /**
  153. * Called when the listener has been successfully executed and returned
  154. * {@code true}. The {@see #isDone} method should return {@code true} by now.
  155. * Designed for inheritance, should be overridden by subclasses or on the
  156. * instances if they care.
  157. */
  158. goog.async.ConditionalDelay.prototype.onSuccess = function() {
  159. // Do nothing by default.
  160. };
  161. /**
  162. * Called when this delayed call is cancelled because the timeout has been
  163. * exceeded, and the listener has never returned {@code true}.
  164. * Designed for inheritance, should be overridden by subclasses or on the
  165. * instances if they care.
  166. */
  167. goog.async.ConditionalDelay.prototype.onFailure = function() {
  168. // Do nothing by default.
  169. };
  170. /**
  171. * A callback function for the underlying {@code goog.async.Delay} object. When
  172. * executed the listener function is called, and if it returns {@code true}
  173. * the delay is stopped and the {@see #onSuccess} method is invoked.
  174. * If the timeout is exceeded the delay is stopped and the
  175. * {@see #onFailure} method is called.
  176. * @private
  177. */
  178. goog.async.ConditionalDelay.prototype.onTick_ = function() {
  179. var successful = this.listener_.call(this.handler_);
  180. if (successful) {
  181. this.isDone_ = true;
  182. this.onSuccess();
  183. } else {
  184. // Try to reschedule the task.
  185. if (this.runUntil_ < 0) {
  186. // No timeout.
  187. this.delay_.start(this.interval_);
  188. } else {
  189. var timeLeft = this.runUntil_ - goog.now();
  190. if (timeLeft <= 0) {
  191. this.onFailure();
  192. } else {
  193. this.delay_.start(Math.min(this.interval_, timeLeft));
  194. }
  195. }
  196. }
  197. };