-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
80 lines (62 loc) · 1.32 KB
/
index.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
var EventEmitter = require('events').EventEmitter;
var now = require('microtime').now;
module.exports =
function FrequencyMeter(targetInterval) {
if (! targetInterval) targetInterval = 1000;
var count = 0;
var maxCount = 10;
var start = now();
var frequency = 0;
var period = targetInterval;
var timeout;
var ee = new EventEmitter();
// happened
ee.happened =
ee.activity =
function happened() {
count ++;
if (count == maxCount) cycle();
};
/// end
ee.end =
function end() {
unschedule();
ee.happened =
ee.activity =
function() {
throw new Error('ended');
}
};
schedule();
return ee;
//// ------
function cycle() {
var t = now();
period = (t - start) / 1000;
frequency = count / period;
// adjust maxCount
maxCount = Math.round(frequency * targetInterval);
frequency = frequency * 1000;
unschedule();
schedule();
ee.emit('frequency', frequency);
count = 0;
start = t;
}
function schedule() {
timeout = setTimeout(function() {
if (count == 0) {
schedule();
ee.emit('frequency', frequency = 0);
} else {
maxCount = count + 1;
}
}, period);
}
function unschedule() {
if (timeout) {
clearTimeout(timeout);
timeout = undefined;
}
}
}