-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
speedometer.js
38 lines (31 loc) · 964 Bytes
/
speedometer.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
// Thanks! https://github.com/mafintosh/speedometer
var tick = 1;
var maxTick = 65535;
var resolution = 4;
var inc = function() {
tick = (tick + 1) & maxTick;
};
var timer = setInterval(inc, (1000 / resolution) | 0);
if (timer.unref) timer.unref();
export default function speedometer(seconds) {
var size = resolution * (seconds || 5);
var buffer = [0];
var pointer = 1;
var last = (tick - 1) & maxTick;
return function(delta) {
var dist = (tick - last) & maxTick;
if (dist > size) dist = size;
last = tick;
while (dist--) {
if (pointer === size) pointer = 0;
buffer[pointer] = buffer[pointer === 0 ? size - 1 : pointer - 1];
pointer++;
}
if (delta) buffer[pointer - 1] += delta;
var top = buffer[pointer - 1];
var btm = buffer.length < size ? 0 : buffer[pointer === size ? 0 : pointer];
return buffer.length < resolution
? top
: (top - btm) * resolution / buffer.length;
};
}