getRequestAnimationFrame.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334
  1. const availablePrefixs = ['moz', 'ms', 'webkit'];
  2. function requestAnimationFramePolyfill() {
  3. let lastTime = 0;
  4. return function (callback) {
  5. const currTime = new Date().getTime();
  6. const timeToCall = Math.max(0, 16 - (currTime - lastTime));
  7. const id = window.setTimeout(function () {
  8. callback(currTime + timeToCall);
  9. }, timeToCall);
  10. lastTime = currTime + timeToCall;
  11. return id;
  12. };
  13. }
  14. export default function getRequestAnimationFrame() {
  15. if (typeof window === 'undefined') {
  16. return () => {};
  17. }
  18. if (window.requestAnimationFrame) {
  19. // https://github.com/vuejs/vue/issues/4465
  20. return window.requestAnimationFrame.bind(window);
  21. }
  22. const prefix = availablePrefixs.filter(key => `${key}RequestAnimationFrame` in window)[0];
  23. return prefix ? window[`${prefix}RequestAnimationFrame`] : requestAnimationFramePolyfill();
  24. }
  25. export function cancelRequestAnimationFrame(id) {
  26. if (typeof window === 'undefined') {
  27. return null;
  28. }
  29. if (window.cancelAnimationFrame) {
  30. return window.cancelAnimationFrame(id);
  31. }
  32. const prefix = availablePrefixs.filter(key => `${key}CancelAnimationFrame` in window || `${key}CancelRequestAnimationFrame` in window)[0];
  33. return prefix ? (window[`${prefix}CancelAnimationFrame`] || window[`${prefix}CancelRequestAnimationFrame`]).call(this, id) : clearTimeout(id);
  34. }