-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
48 lines (36 loc) · 941 Bytes
/
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
var EventEmitter = require('events').EventEmitter;
module.exports = periodic;
function periodic (interval) {
if (!(this instanceof periodic)) return new periodic(interval);
EventEmitter.call(this);
this.interval = interval;
this.ended = false;
this.timeout;
var self = this;
setTimeout(function () {
self.repeat();
});
}
inherits(periodic, EventEmitter);
periodic.prototype.repeat = function () {
if (this.ended) return;
var start = +new Date();
var tick = 0;
var dt = (start + this.interval * ++tick) - +new Date();
if (dt < 0) dt = 0;
var self = this;
self.timeout = setTimeout(function () {
self.repeat();
}, dt);
this.emit('tick');
}
periodic.prototype.end = function () {
this.ended = true;
if (this.timeout) clearTimeout(this.timeout);
}
function inherits (a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};