|
1 |
| -let lastTime = 0; |
2 |
| -const prefixes = 'webkit moz ms o'.split(' '); // 各浏览器前缀 |
| 1 | +let lastTime = 0 |
| 2 | +const prefixes = 'webkit moz ms o'.split(' ') // 各浏览器前缀 |
| 3 | +let requestAnimationFrame |
| 4 | +let cancelAnimationFrame |
| 5 | +let prefix |
| 6 | +const isServer = typeof window === 'undefined' |
3 | 7 |
|
4 |
| -let requestAnimationFrame = window.requestAnimationFrame; |
5 |
| -let cancelAnimationFrame = window.cancelAnimationFrame; |
6 |
| - |
7 |
| -let prefix; |
8 |
| -// 通过遍历各浏览器前缀,来得到requestAnimationFrame和cancelAnimationFrame在当前浏览器的实现形式 |
9 |
| -for (let i = 0; i < prefixes.length; i++) { |
10 |
| - if (requestAnimationFrame && cancelAnimationFrame) { break; } |
11 |
| - prefix = prefixes[i]; |
12 |
| - requestAnimationFrame = requestAnimationFrame || window[prefix + 'RequestAnimationFrame']; |
13 |
| - cancelAnimationFrame = cancelAnimationFrame || window[prefix + 'CancelAnimationFrame'] || window[prefix + 'CancelRequestAnimationFrame']; |
| 8 | +if (!isServer) { |
| 9 | + requestAnimationFrame = window.requestAnimationFrame |
| 10 | + cancelAnimationFrame = window.cancelAnimationFrame |
| 11 | + // 通过遍历各浏览器前缀,来得到requestAnimationFrame和cancelAnimationFrame在当前浏览器的实现形式 |
| 12 | + for (let i = 0; i < prefixes.length; i++) { |
| 13 | + if (requestAnimationFrame && cancelAnimationFrame) { break } |
| 14 | + prefix = prefixes[i] |
| 15 | + requestAnimationFrame = requestAnimationFrame || window[prefix + 'RequestAnimationFrame'] |
| 16 | + cancelAnimationFrame = cancelAnimationFrame || window[prefix + 'CancelAnimationFrame'] || window[prefix + 'CancelRequestAnimationFrame'] |
| 17 | + } |
14 | 18 | }
|
15 | 19 |
|
16 | 20 | // 如果当前浏览器不支持requestAnimationFrame和cancelAnimationFrame,则会退到setTimeout
|
17 | 21 | if (!requestAnimationFrame || !cancelAnimationFrame) {
|
18 | 22 | requestAnimationFrame = function(callback) {
|
19 |
| - const currTime = new Date().getTime(); |
20 |
| - // 为了使setTimteout的尽可能的接近每秒60帧的效果 |
21 |
| - const timeToCall = Math.max(0, 16 - (currTime - lastTime)); |
22 |
| - const id = window.setTimeout(() => { |
23 |
| - callback(currTime + timeToCall); |
24 |
| - }, timeToCall); |
25 |
| - lastTime = currTime + timeToCall; |
26 |
| - return id; |
27 |
| - }; |
| 23 | + const currTime = new Date().getTime() |
| 24 | + // 为了使setTimteout的尽可能的接近每秒60帧的效果 |
| 25 | + const timeToCall = Math.max(0, 16 - (currTime - lastTime)) |
| 26 | + const id = window.setTimeout(() => { |
| 27 | + callback(currTime + timeToCall) |
| 28 | + }, timeToCall) |
| 29 | + lastTime = currTime + timeToCall |
| 30 | + return id |
| 31 | + } |
28 | 32 |
|
29 | 33 | cancelAnimationFrame = function(id) {
|
30 |
| - window.clearTimeout(id); |
31 |
| - }; |
| 34 | + window.clearTimeout(id) |
| 35 | + } |
32 | 36 | }
|
33 | 37 |
|
34 | 38 | export { requestAnimationFrame, cancelAnimationFrame }
|
0 commit comments