animationdelay.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // Copyright 2012 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 A delayed callback that pegs to the next animation frame
  16. * instead of a user-configurable timeout.
  17. *
  18. * @author nicksantos@google.com (Nick Santos)
  19. */
  20. goog.provide('goog.async.AnimationDelay');
  21. goog.require('goog.Disposable');
  22. goog.require('goog.events');
  23. goog.require('goog.functions');
  24. // TODO(nicksantos): Should we factor out the common code between this and
  25. // goog.async.Delay? I'm not sure if there's enough code for this to really
  26. // make sense. Subclassing seems like the wrong approach for a variety of
  27. // reasons. Maybe there should be a common interface?
  28. /**
  29. * A delayed callback that pegs to the next animation frame
  30. * instead of a user configurable timeout. By design, this should have
  31. * the same interface as goog.async.Delay.
  32. *
  33. * Uses requestAnimationFrame and friends when available, but falls
  34. * back to a timeout of goog.async.AnimationDelay.TIMEOUT.
  35. *
  36. * For more on requestAnimationFrame and how you can use it to create smoother
  37. * animations, see:
  38. * @see http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  39. *
  40. * @param {function(this:THIS, number)} listener Function to call
  41. * when the delay completes. Will be passed the timestamp when it's called,
  42. * in unix ms.
  43. * @param {Window=} opt_window The window object to execute the delay in.
  44. * Defaults to the global object.
  45. * @param {THIS=} opt_handler The object scope to invoke the function in.
  46. * @template THIS
  47. * @constructor
  48. * @struct
  49. * @extends {goog.Disposable}
  50. * @final
  51. */
  52. goog.async.AnimationDelay = function(listener, opt_window, opt_handler) {
  53. goog.async.AnimationDelay.base(this, 'constructor');
  54. /**
  55. * Identifier of the active delay timeout, or event listener,
  56. * or null when inactive.
  57. * @private {goog.events.Key|number}
  58. */
  59. this.id_ = null;
  60. /**
  61. * If we're using dom listeners.
  62. * @private {?boolean}
  63. */
  64. this.usingListeners_ = false;
  65. /**
  66. * The function that will be invoked after a delay.
  67. * @const
  68. * @private
  69. */
  70. this.listener_ = listener;
  71. /**
  72. * The object context to invoke the callback in.
  73. * @const
  74. * @private {(THIS|undefined)}
  75. */
  76. this.handler_ = opt_handler;
  77. /**
  78. * @private {Window}
  79. */
  80. this.win_ = opt_window || window;
  81. /**
  82. * Cached callback function invoked when the delay finishes.
  83. * @private {function()}
  84. */
  85. this.callback_ = goog.bind(this.doAction_, this);
  86. };
  87. goog.inherits(goog.async.AnimationDelay, goog.Disposable);
  88. /**
  89. * Default wait timeout for animations (in milliseconds). Only used for timed
  90. * animation, which uses a timer (setTimeout) to schedule animation.
  91. *
  92. * @type {number}
  93. * @const
  94. */
  95. goog.async.AnimationDelay.TIMEOUT = 20;
  96. /**
  97. * Name of event received from the requestAnimationFrame in Firefox.
  98. *
  99. * @type {string}
  100. * @const
  101. * @private
  102. */
  103. goog.async.AnimationDelay.MOZ_BEFORE_PAINT_EVENT_ = 'MozBeforePaint';
  104. /**
  105. * Starts the delay timer. The provided listener function will be called
  106. * before the next animation frame.
  107. */
  108. goog.async.AnimationDelay.prototype.start = function() {
  109. this.stop();
  110. this.usingListeners_ = false;
  111. var raf = this.getRaf_();
  112. var cancelRaf = this.getCancelRaf_();
  113. if (raf && !cancelRaf && this.win_.mozRequestAnimationFrame) {
  114. // Because Firefox (Gecko) runs animation in separate threads, it also saves
  115. // time by running the requestAnimationFrame callbacks in that same thread.
  116. // Sadly this breaks the assumption of implicit thread-safety in JS, and can
  117. // thus create thread-based inconsistencies on counters etc.
  118. //
  119. // Calling cycleAnimations_ using the MozBeforePaint event instead of as
  120. // callback fixes this.
  121. //
  122. // Trigger this condition only if the mozRequestAnimationFrame is available,
  123. // but not the W3C requestAnimationFrame function (as in draft) or the
  124. // equivalent cancel functions.
  125. this.id_ = goog.events.listen(
  126. this.win_, goog.async.AnimationDelay.MOZ_BEFORE_PAINT_EVENT_,
  127. this.callback_);
  128. this.win_.mozRequestAnimationFrame(null);
  129. this.usingListeners_ = true;
  130. } else if (raf && cancelRaf) {
  131. this.id_ = raf.call(this.win_, this.callback_);
  132. } else {
  133. this.id_ = this.win_.setTimeout(
  134. // Prior to Firefox 13, Gecko passed a non-standard parameter
  135. // to the callback that we want to ignore.
  136. goog.functions.lock(this.callback_), goog.async.AnimationDelay.TIMEOUT);
  137. }
  138. };
  139. /**
  140. * Starts the delay timer if it's not already active.
  141. */
  142. goog.async.AnimationDelay.prototype.startIfNotActive = function() {
  143. if (!this.isActive()) {
  144. this.start();
  145. }
  146. };
  147. /**
  148. * Stops the delay timer if it is active. No action is taken if the timer is not
  149. * in use.
  150. */
  151. goog.async.AnimationDelay.prototype.stop = function() {
  152. if (this.isActive()) {
  153. var raf = this.getRaf_();
  154. var cancelRaf = this.getCancelRaf_();
  155. if (raf && !cancelRaf && this.win_.mozRequestAnimationFrame) {
  156. goog.events.unlistenByKey(this.id_);
  157. } else if (raf && cancelRaf) {
  158. cancelRaf.call(this.win_, /** @type {number} */ (this.id_));
  159. } else {
  160. this.win_.clearTimeout(/** @type {number} */ (this.id_));
  161. }
  162. }
  163. this.id_ = null;
  164. };
  165. /**
  166. * Fires delay's action even if timer has already gone off or has not been
  167. * started yet; guarantees action firing. Stops the delay timer.
  168. */
  169. goog.async.AnimationDelay.prototype.fire = function() {
  170. this.stop();
  171. this.doAction_();
  172. };
  173. /**
  174. * Fires delay's action only if timer is currently active. Stops the delay
  175. * timer.
  176. */
  177. goog.async.AnimationDelay.prototype.fireIfActive = function() {
  178. if (this.isActive()) {
  179. this.fire();
  180. }
  181. };
  182. /**
  183. * @return {boolean} True if the delay is currently active, false otherwise.
  184. */
  185. goog.async.AnimationDelay.prototype.isActive = function() {
  186. return this.id_ != null;
  187. };
  188. /**
  189. * Invokes the callback function after the delay successfully completes.
  190. * @private
  191. */
  192. goog.async.AnimationDelay.prototype.doAction_ = function() {
  193. if (this.usingListeners_ && this.id_) {
  194. goog.events.unlistenByKey(this.id_);
  195. }
  196. this.id_ = null;
  197. // We are not using the timestamp returned by requestAnimationFrame
  198. // because it may be either a Date.now-style time or a
  199. // high-resolution time (depending on browser implementation). Using
  200. // goog.now() will ensure that the timestamp used is consistent and
  201. // compatible with goog.fx.Animation.
  202. this.listener_.call(this.handler_, goog.now());
  203. };
  204. /** @override */
  205. goog.async.AnimationDelay.prototype.disposeInternal = function() {
  206. this.stop();
  207. goog.async.AnimationDelay.base(this, 'disposeInternal');
  208. };
  209. /**
  210. * @return {?function(function(number)): number} The requestAnimationFrame
  211. * function, or null if not available on this browser.
  212. * @private
  213. */
  214. goog.async.AnimationDelay.prototype.getRaf_ = function() {
  215. var win = this.win_;
  216. return win.requestAnimationFrame || win.webkitRequestAnimationFrame ||
  217. win.mozRequestAnimationFrame || win.oRequestAnimationFrame ||
  218. win.msRequestAnimationFrame || null;
  219. };
  220. /**
  221. * @return {?function(number): undefined} The cancelAnimationFrame function,
  222. * or null if not available on this browser.
  223. * @private
  224. */
  225. goog.async.AnimationDelay.prototype.getCancelRaf_ = function() {
  226. var win = this.win_;
  227. return win.cancelAnimationFrame || win.cancelRequestAnimationFrame ||
  228. win.webkitCancelRequestAnimationFrame ||
  229. win.mozCancelRequestAnimationFrame || win.oCancelRequestAnimationFrame ||
  230. win.msCancelRequestAnimationFrame || null;
  231. };