Source: Core/requestAnimationFrame.js

  1. /*global define*/
  2. define([
  3. './defined',
  4. './getTimestamp'
  5. ], function(
  6. defined,
  7. getTimestamp) {
  8. 'use strict';
  9. if (typeof window === 'undefined') {
  10. return;
  11. }
  12. var implementation = window.requestAnimationFrame;
  13. (function() {
  14. // look for vendor prefixed function
  15. if (!defined(implementation)) {
  16. var vendors = ['webkit', 'moz', 'ms', 'o'];
  17. var i = 0;
  18. var len = vendors.length;
  19. while (i < len && !defined(implementation)) {
  20. implementation = window[vendors[i] + 'RequestAnimationFrame'];
  21. ++i;
  22. }
  23. }
  24. // build an implementation based on setTimeout
  25. if (!defined(implementation)) {
  26. var msPerFrame = 1000.0 / 60.0;
  27. var lastFrameTime = 0;
  28. implementation = function(callback) {
  29. var currentTime = getTimestamp();
  30. // schedule the callback to target 60fps, 16.7ms per frame,
  31. // accounting for the time taken by the callback
  32. var delay = Math.max(msPerFrame - (currentTime - lastFrameTime), 0);
  33. lastFrameTime = currentTime + delay;
  34. return setTimeout(function() {
  35. callback(lastFrameTime);
  36. }, delay);
  37. };
  38. }
  39. })();
  40. /**
  41. * A browser-independent function to request a new animation frame. This is used to create
  42. * an application's draw loop as shown in the example below.
  43. *
  44. * @exports requestAnimationFrame
  45. *
  46. * @param {requestAnimationFrame~Callback} callback The function to call when the next frame should be drawn.
  47. * @returns {Number} An ID that can be passed to {@link cancelAnimationFrame} to cancel the request.
  48. *
  49. *
  50. * @example
  51. * // Create a draw loop using requestAnimationFrame. The
  52. * // tick callback function is called for every animation frame.
  53. * function tick() {
  54. * scene.render();
  55. * Cesium.requestAnimationFrame(tick);
  56. * }
  57. * tick();
  58. *
  59. * @see {@link http://www.w3.org/TR/animation-timing/#the-WindowAnimationTiming-interface|The WindowAnimationTiming interface}
  60. */
  61. function requestAnimationFrame(callback) {
  62. // we need this extra wrapper function because the native requestAnimationFrame
  63. // functions must be invoked on the global scope (window), which is not the case
  64. // if invoked as Cesium.requestAnimationFrame(callback)
  65. return implementation(callback);
  66. }
  67. /**
  68. * A function that will be called when the next frame should be drawn.
  69. * @callback requestAnimationFrame~Callback
  70. *
  71. * @param {Number} timestamp A timestamp for the frame, in milliseconds.
  72. */
  73. return requestAnimationFrame;
  74. });