forked from marmelab/gremlins.js
-
Notifications
You must be signed in to change notification settings - Fork 3
/
fps.js
109 lines (97 loc) · 3.13 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* The fps mogwai logs the number of frames per seconds (FPS) of the browser
*
* The normal (and maximal) FPS rate is 60. It decreases when the browser is
* busy refreshing the layout, or executing JavaScript.
*
* This mogwai logs with the error level once the FPS rate drops below 10.
*
* var fpsMogwai = gremlins.mogwais.fps();
* horde.mogwai(fpsMogwai);
*
* The fps mogwai can be customized as follows:
*
* fpsMogwai.delay(500); // the interval for FPS measurements
* fpsMogwai.levelSelector(function(fps) { // select logging level according to fps value });
* fpsMogwai.logger(loggerObject); // inject a logger
*
* Example usage:
*
* horde.mogwai(gremlins.mogwais.fps()
* .delay(250)
* .levelSelector(function(fps) {
* if (fps < 5) return 'error';
* if (fps < 10) return 'warn';
* return 'log';
* })
* );
*/
define(function(require) {
"use strict";
var configurable = require('../utils/configurable');
var LoggerRequiredException = require('../exceptions/loggerRequired');
return function() {
if (!window.requestAnimationFrame) {
// shim layer with setTimeout fallback
window.requestAnimationFrame =
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
}
function defaultLevelSelector(fps) {
if (fps < 10) return 'error';
if (fps < 20) return 'warn';
return 'log';
}
/**
* @mixin
*/
var config = {
delay: 500, // how often should the fps be measured
levelSelector: defaultLevelSelector,
logger: null
};
var initialTime = -Infinity; // force initial measure
var enabled;
function loop(time) {
if ((time - initialTime) > config.delay) {
measureFPS(time);
initialTime = time;
}
if (!enabled) return;
window.requestAnimationFrame(loop);
}
function measureFPS() {
var lastTime;
function init(time) {
lastTime = time;
window.requestAnimationFrame(measure);
}
function measure(time) {
var fps = (time - lastTime < 16) ? 60 : 1000/(time - lastTime);
var level = config.levelSelector(fps);
config.logger[level]('mogwai ', 'fps ', fps);
}
window.requestAnimationFrame(init);
}
/**
* @mixes config
*/
function fpsMogwai() {
if (!config.logger) {
throw new LoggerRequiredException();
}
enabled = true;
window.requestAnimationFrame(loop);
}
fpsMogwai.cleanUp = function() {
enabled = false;
return fpsMogwai;
};
configurable(fpsMogwai, config);
return fpsMogwai;
};
});