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