animation.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { isServer } from '/@/utils/is';
  2. let lastTime = 0;
  3. const prefixes = 'webkit moz ms o'.split(' ');
  4. let requestAnimationFrame: typeof window.requestAnimationFrame;
  5. let cancelAnimationFrame: typeof window.cancelAnimationFrame;
  6. (() => {
  7. const NO_LOOP: any = () => {};
  8. const getWindowFrame = (name: string) => {
  9. return name as any;
  10. };
  11. if (isServer) {
  12. requestAnimationFrame = cancelAnimationFrame = NO_LOOP;
  13. } else {
  14. requestAnimationFrame = window.requestAnimationFrame;
  15. cancelAnimationFrame = window.cancelAnimationFrame;
  16. let prefix;
  17. for (let i = 0; i < prefixes.length; i++) {
  18. if (requestAnimationFrame && cancelAnimationFrame) {
  19. break;
  20. }
  21. prefix = prefixes[i];
  22. requestAnimationFrame =
  23. requestAnimationFrame || window[getWindowFrame(prefix + 'RequestAnimationFrame')];
  24. cancelAnimationFrame =
  25. cancelAnimationFrame ||
  26. window[getWindowFrame(prefix + 'CancelAnimationFrame')] ||
  27. window[getWindowFrame(prefix + 'CancelRequestAnimationFrame')];
  28. }
  29. // If the current browser does not support requestAnimationFrame and cancelAnimationFrame, it will fall back to setTimeout
  30. if (!requestAnimationFrame || !cancelAnimationFrame) {
  31. requestAnimationFrame = function (callback: Fn) {
  32. const currTime = new Date().getTime();
  33. const timeToCall = Math.max(0, 16 - (currTime - lastTime));
  34. const id = window.setTimeout(() => {
  35. /* eslint-disable-next-line */
  36. callback(currTime + timeToCall);
  37. }, timeToCall);
  38. lastTime = currTime + timeToCall;
  39. return id;
  40. };
  41. cancelAnimationFrame = function (id: number) {
  42. window.clearTimeout(id);
  43. };
  44. }
  45. }
  46. })();
  47. export { requestAnimationFrame, cancelAnimationFrame };