Skip to content

Commit 46ba42d

Browse files
committed
suppport ssr
1 parent 531c1fc commit 46ba42d

File tree

1 file changed

+27
-23
lines changed

1 file changed

+27
-23
lines changed

src/requestAnimationFrame.js

+27-23
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,38 @@
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'
37

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+
}
1418
}
1519

1620
// 如果当前浏览器不支持requestAnimationFrame和cancelAnimationFrame,则会退到setTimeout
1721
if (!requestAnimationFrame || !cancelAnimationFrame) {
1822
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+
}
2832

2933
cancelAnimationFrame = function(id) {
30-
window.clearTimeout(id);
31-
};
34+
window.clearTimeout(id)
35+
}
3236
}
3337

3438
export { requestAnimationFrame, cancelAnimationFrame }

0 commit comments

Comments
 (0)