-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathd-wrapper-class.js
59 lines (51 loc) · 1.03 KB
/
d-wrapper-class.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
'use strict';
class Wrapper {
constructor(limit, fn) {
this.count = limit;
this.calls = 0;
this.pause = false;
this.fn = fn;
this.timedout = false;
}
call(...args) {
if (this.timedout) return;
if (this.calls === this.count) throw new Error('Limit reached');
else if (!this.pause) {
this.calls++;
return this.fn(...args);
}
}
stop() {
if (this.pause) this.pause = false;
else this.pause = true;
return this;
}
timeout(msec) {
let timer = setTimeout(() => {
if (timer) {
timer = null;
console.log('Function timedout');
this.timedout = true;
}
}, msec);
return this;
}
print() {
console.log(`Calls: ${this.calls}\nFunction: ${this.fn}`);
return this;
}
}
//USAGE
const fn = par => {
console.log('Function called, par:', par);
};
const fnLim = new Wrapper(3, fn);
fnLim.call(1);
fnLim.print();
fnLim.stop();
fnLim.call(2);
fnLim
.stop()
.timeout(100);
setTimeout(() => fnLim.call(3), 150);
fnLim.call(4);