forked from pgte/frequency-meter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
58 lines (47 loc) · 1.17 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
var EventEmitter = require('events').EventEmitter;
var now = require('microtime').now;
module.exports =
function FrequencyMeter(samplingWindow, ntfyInterval) {
if (! samplingWindow) samplingWindow = 1000;
if (! ntfyInterval) ntfyInterval = samplingWindow;
var events = [];
var timeout;
var ee = new EventEmitter();
// happened
ee.happened =
ee.activity =
function happened() {
events.push(now());
//console.log("happened, events.length=="+events.length);
};
/// end
ee.end =
function end() {
unschedule();
ee.happened =
ee.activity =
function() {
throw new Error('ended');
};
};
schedule();
return ee;
//// ------
function schedule() {
timeout = setInterval(function() {
// filter out old events
events = events.filter( function(x) {
return (x > now() - 1000 * samplingWindow);
});
var frequency = (1000 * events.length / samplingWindow);
// console.log("fire in the hole! freq="+frequency);
ee.emit('frequency', frequency);
}, ntfyInterval);
}
function unschedule() {
if (timeout) {
clearInterval(timeout);
timeout = undefined;
}
}
};