-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathb-optimzed.js
73 lines (65 loc) · 1.23 KB
/
b-optimzed.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
'use strict';
const wrap = (f) => {
let limit = 0;
let counter = 0;
let timer = null;
let fn = f;
const wrapper = (...args) => {
//console.dir({ limit, counter, fn, args });
if (!fn) return null;
if (limit && counter === limit) {
limit = 0;
counter = 0;
wrapper.cancel();
return null;
}
const res = fn(...args);
counter++;
return res;
};
const methods = {
cancel() {
fn = null;
return this;
},
resume() {
if (!fn) fn = f;
return this;
},
timeout(msec) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => this.cancel(), msec);
return this;
},
limit(count) {
limit = count || 0;
counter = 0;
return this;
},
};
return Object.assign(wrapper, methods);
};
// Usage
const fn = (par) => {
console.log('Function called, par:', par);
};
const fn2 = wrap(fn).timeout(200).limit(3);
fn2('1st');
setTimeout(() => {
fn2('2nd');
fn2.cancel();
fn2('3rd');
fn2.resume();
fn2('4th');
fn2.timeout(200);
setTimeout(() => {
fn2('5th');
setTimeout(() => {
fn2.limit(1);
fn2('6th');
fn2('7th');
fn2.resume();
fn2('8th');
}, 150);
}, 150);
}, 150);