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