polyfill.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2014 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 polyfill for window.requestAnimationFrame and
  16. * window.cancelAnimationFrame.
  17. * Code based on https://gist.github.com/paulirish/1579671
  18. */
  19. goog.provide('goog.dom.animationFrame.polyfill');
  20. /**
  21. * @define {boolean} If true, will install the requestAnimationFrame polyfill.
  22. */
  23. goog.define('goog.dom.animationFrame.polyfill.ENABLED', true);
  24. /**
  25. * Installs the requestAnimationFrame (and cancelAnimationFrame) polyfill.
  26. */
  27. goog.dom.animationFrame.polyfill.install = function() {
  28. if (goog.dom.animationFrame.polyfill.ENABLED) {
  29. var vendors = ['ms', 'moz', 'webkit', 'o'];
  30. for (var i = 0, v; v = vendors[i] && !goog.global.requestAnimationFrame;
  31. ++i) {
  32. goog.global.requestAnimationFrame =
  33. goog.global[v + 'RequestAnimationFrame'];
  34. goog.global.cancelAnimationFrame =
  35. goog.global[v + 'CancelAnimationFrame'] ||
  36. goog.global[v + 'CancelRequestAnimationFrame'];
  37. }
  38. if (!goog.global.requestAnimationFrame) {
  39. var lastTime = 0;
  40. goog.global.requestAnimationFrame = function(callback) {
  41. var currTime = new Date().getTime();
  42. var timeToCall = Math.max(0, 16 - (currTime - lastTime));
  43. lastTime = currTime + timeToCall;
  44. return goog.global.setTimeout(function() {
  45. callback(currTime + timeToCall);
  46. }, timeToCall);
  47. };
  48. if (!goog.global.cancelAnimationFrame) {
  49. goog.global.cancelAnimationFrame = function(id) { clearTimeout(id); };
  50. }
  51. }
  52. }
  53. };