-
Notifications
You must be signed in to change notification settings - Fork 427
/
fps.js
57 lines (49 loc) · 1.47 KB
/
fps.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const NEXT_FRAME_MS = 16;
const getDefaultConfig = () => {
const defaultLevelSelector = (fps) => {
if (fps < 10) return 'error';
if (fps < 20) return 'warn';
return 'log';
};
return {
delay: 500, // how often should the fps be measured
levelSelector: defaultLevelSelector,
};
};
export default (userConfig) => ({ logger, window }) => {
const config = { ...getDefaultConfig(), ...userConfig };
let initialTime = -Infinity; // force initial measure
let enabled;
const loop = (time) => {
if (time - initialTime > config.delay) {
measureFPS(time);
initialTime = time;
}
if (!enabled) return;
window.requestAnimationFrame(loop);
};
const measureFPS = () => {
let lastTime;
const init = (time) => {
lastTime = time;
window.requestAnimationFrame(measure);
};
const measure = (time) => {
const fps = time - lastTime < NEXT_FRAME_MS ? 60 : 1000 / (time - lastTime);
const level = config.levelSelector(fps);
if (logger) {
logger[level]('mogwai ', 'fps ', fps);
}
};
window.requestAnimationFrame(init);
};
const fpsMogwai = () => {
enabled = true;
window.requestAnimationFrame(loop);
};
fpsMogwai.cleanUp = () => {
enabled = false;
return fpsMogwai;
};
return fpsMogwai;
};