-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-watchers.js
31 lines (27 loc) · 912 Bytes
/
01-watchers.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
/* eslint-disable func-names, no-console */
function Watcher(fn, interval, type, ...args) {
this.fn = fn;
this.interval = interval;
this.type = type;
this.args = args;
}
Watcher.prototype.start = function () {
if (this.intervalID != null) return; // either null or undefined
this.intervalID = setInterval(this.fn, this.interval, ...this.args);
this.startTime = new Date().getTime();
};
Watcher.prototype.stop = function () {
if (this.intervalID == null) return; // either null or undefined
clearInterval(this.intervalID);
console.log(`Ran for ${this.duration()} seconds`);
this.intervalID = null;
this.startTime = null;
};
Watcher.prototype.restart = function () {
this.stop();
this.start();
};
Watcher.prototype.duration = function () {
if (this.startTime == null) return;
return Math.floor((new Date().getTime() - this.startTime) / 1000);
};