0
# stats.js
1
2
stats.js is a lightweight JavaScript performance monitoring library that provides a visual widget for displaying real-time FPS (frames per second) and frame render time statistics. It creates a compact DOM-based overlay that can be embedded in web applications for performance debugging and optimization.
3
4
## Package Information
5
6
- **Package Name**: stats.js
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install stats.js`
10
11
## Core Imports
12
13
```javascript
14
// CommonJS
15
const Stats = require('stats.js');
16
17
// ES Modules (if using a bundler)
18
import Stats from 'stats.js';
19
```
20
21
Browser direct include:
22
```html
23
<script src="path/to/stats.min.js"></script>
24
<!-- Stats constructor is available globally -->
25
```
26
27
## Basic Usage
28
29
```javascript
30
// Create a new performance monitor
31
const stats = new Stats();
32
33
// Position the widget (usually top-left corner)
34
stats.domElement.style.position = 'absolute';
35
stats.domElement.style.left = '0px';
36
stats.domElement.style.top = '0px';
37
document.body.appendChild(stats.domElement);
38
39
// Option 1: Manual measurement
40
function gameLoop() {
41
stats.begin();
42
43
// Your performance-critical code here
44
// (game rendering, calculations, etc.)
45
46
stats.end();
47
requestAnimationFrame(gameLoop);
48
}
49
50
// Option 2: Convenience method
51
function gameLoop() {
52
stats.update(); // Equivalent to calling end() then begin()
53
54
// Your performance-critical code here
55
56
requestAnimationFrame(gameLoop);
57
}
58
59
// Start the loop
60
requestAnimationFrame(gameLoop);
61
```
62
63
## Architecture
64
65
stats.js is built around several key design patterns:
66
67
- **DOM Widget System**: Creates a self-contained visual widget using dynamically generated DOM elements with inline styling
68
- **Dual Display Modes**: Interactive toggle between FPS (frames per second) and MS (milliseconds per frame) measurement modes
69
- **Performance Timing**: Uses high-precision timing APIs (`performance.now()` with `Date.now()` fallback) for accurate measurements
70
- **Real-time Visualization**: Live-updating graph bars that show performance history over time
71
- **Event-driven Interaction**: Mouse click handling for mode switching with visual feedback
72
- **Modular Measurement**: Flexible begin/end pattern allows measurement of arbitrary code blocks
73
74
## Capabilities
75
76
### Stats Constructor
77
78
Creates a new performance monitoring widget instance with interactive display modes.
79
80
```javascript { .api }
81
/**
82
* Creates a new Stats performance monitor widget
83
* @constructor
84
* @returns {Object} Stats instance with methods and properties
85
*/
86
function Stats();
87
```
88
89
The widget automatically creates a visual display with:
90
- **FPS Mode (Mode 0)**: Shows frames per second with min/max tracking (blue/cyan theme)
91
- **MS Mode (Mode 1)**: Shows milliseconds per frame with min/max tracking (green theme)
92
- **Interactive Toggle**: Click the widget to switch between modes
93
94
### Instance Properties
95
96
```javascript { .api }
97
interface StatsInstance {
98
/** Library revision number (currently 13) */
99
REVISION: number;
100
101
/** The widget's container DOM element that can be appended to the document */
102
domElement: HTMLDivElement;
103
}
104
```
105
106
### Performance Measurement
107
108
Core methods for measuring code performance within a frame or time period.
109
110
```javascript { .api }
111
/**
112
* Marks the beginning of a performance measurement frame
113
* Call before the code you want to measure
114
*/
115
begin(): void;
116
117
/**
118
* Marks the end of a performance measurement frame and updates display
119
* Call after the code you want to measure
120
* @returns {number} Current timestamp (from performance.now() or Date.now())
121
*/
122
end(): number;
123
124
/**
125
* Convenience method that calls end() then immediately begins a new measurement
126
* Useful for continuous monitoring in animation loops
127
*/
128
update(): void;
129
```
130
131
**Usage Examples:**
132
133
```javascript
134
const stats = new Stats();
135
document.body.appendChild(stats.domElement);
136
137
// Measuring a specific operation
138
stats.begin();
139
performExpensiveCalculation();
140
stats.end();
141
142
// Measuring in an animation loop
143
function animate() {
144
stats.begin();
145
146
// Render scene, update game logic, etc.
147
renderScene();
148
updatePhysics();
149
150
stats.end();
151
requestAnimationFrame(animate);
152
}
153
154
// Alternative using update() method
155
function animate() {
156
stats.update();
157
158
// Your code here runs after measurement ends and new one begins
159
renderScene();
160
updatePhysics();
161
162
requestAnimationFrame(animate);
163
}
164
```
165
166
### Display Mode Control
167
168
Control which performance metric is displayed in the widget.
169
170
```javascript { .api }
171
/**
172
* Sets the display mode of the performance monitor
173
* @param {number} value - Display mode (0 = FPS mode, 1 = MS mode)
174
*/
175
setMode(value: number): void;
176
```
177
178
**Usage Examples:**
179
180
```javascript
181
const stats = new Stats();
182
183
// Start in FPS mode (default)
184
stats.setMode(0);
185
186
// Switch to milliseconds mode
187
stats.setMode(1);
188
189
// Toggle between modes programmatically
190
let currentMode = 0;
191
function toggleMode() {
192
currentMode = (currentMode + 1) % 2;
193
stats.setMode(currentMode);
194
}
195
```
196
197
## Display Modes
198
199
### FPS Mode (Mode 0)
200
- **Purpose**: Displays frames rendered per second with minimum and maximum tracking
201
- **Color Scheme**: Blue/cyan background (#002, #0ff)
202
- **Interpretation**: Higher numbers indicate better performance
203
- **Graph**: Real-time histogram showing FPS variations over time
204
205
### MS Mode (Mode 1)
206
- **Purpose**: Displays milliseconds needed to render each frame with min/max tracking
207
- **Color Scheme**: Green background (#020, #0f0)
208
- **Interpretation**: Lower numbers indicate better performance
209
- **Graph**: Real-time histogram showing frame time variations
210
211
## Styling and Theming
212
213
The widget can be customized using CSS by targeting specific element IDs:
214
215
```css
216
/* Main container */
217
#stats {
218
width: 80px;
219
opacity: 0.9;
220
cursor: pointer;
221
}
222
223
/* FPS mode styling */
224
#fps { /* Container for FPS display */ }
225
#fpsText { /* FPS text label */ }
226
#fpsGraph { /* FPS graph container */ }
227
228
/* MS mode styling */
229
#ms { /* Container for MS display */ }
230
#msText { /* MS text label */ }
231
#msGraph { /* MS graph container */ }
232
```
233
234
## Browser Compatibility
235
236
- **Timing API**: Uses `performance.now()` when available, falls back to `Date.now()`
237
- **DOM Requirements**: Requires `document.createElement` and basic DOM manipulation
238
- **Module Support**: Works with CommonJS (`module.exports`) and global variable patterns
239
- **Zero Dependencies**: No external libraries required
240
241
## Integration Patterns
242
243
### Game Development
244
```javascript
245
const stats = new Stats();
246
stats.domElement.style.position = 'fixed';
247
stats.domElement.style.top = '0';
248
stats.domElement.style.right = '0';
249
stats.domElement.style.zIndex = '10000';
250
document.body.appendChild(stats.domElement);
251
252
function gameLoop(timestamp) {
253
stats.begin();
254
255
updateGame(timestamp);
256
renderGame();
257
258
stats.end();
259
requestAnimationFrame(gameLoop);
260
}
261
```
262
263
### Web Application Monitoring
264
```javascript
265
// Monitor specific operations
266
function monitoredFunction() {
267
stats.begin();
268
try {
269
// Heavy computation or rendering
270
processLargeDataSet();
271
updateUI();
272
} finally {
273
stats.end(); // Ensure measurement ends even if errors occur
274
}
275
}
276
277
// Monitor animation performance
278
function smoothAnimation() {
279
stats.update();
280
// Animation code here
281
animateElements();
282
requestAnimationFrame(smoothAnimation);
283
}
284
```
285
286
### Development Debug Tool
287
```javascript
288
// Only show stats in development
289
if (process.env.NODE_ENV === 'development') {
290
const stats = new Stats();
291
stats.setMode(1); // Start with MS mode for development
292
document.body.appendChild(stats.domElement);
293
294
// Make it draggable or add toggle button
295
stats.domElement.style.position = 'fixed';
296
stats.domElement.style.top = '10px';
297
stats.domElement.style.left = '10px';
298
stats.domElement.style.zIndex = '9999';
299
}
300
```