-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
115 lines (98 loc) · 1.85 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
'use strict';
;(function(exports) {
exports.throttle = function(func, wait) {
let savedThis = null;
let savedArgs = null;
let timer = null;
/**
* Throttle function
*/
function throttle() {
/**
* Invoke function and clear state
*/
function run() {
throttle.flush();
savedThis = null;
savedArgs = null;
timer = null;
}
/**
* Set timer to execute func
*/
function setTimer() {
timer = setTimeout(function() {
if (savedArgs) {
run();
setTimer();
}
}, wait);
}
savedThis = this;
savedArgs = arguments;
if (!timer) {
run(); // first run
setTimer();
}
}
/**
* Immediately invoke function
*/
throttle.flush = function() {
func.apply(savedThis, savedArgs);
};
/**
* Cancel delayed func invocations
*/
throttle.cancel = function() {
if (timer) {
clearTimeout(timer);
timer = null;
}
};
return throttle;
};
exports.debounce = function(func, wait) {
let savedThis = null;
let savedArgs = null;
let timer = null;
/**
* Debounce function
*/
function debounce() {
/**
* Set new timeout for function
*/
function setTimer() {
timer = setTimeout(function() {
debounce.flush();
timer = null;
}, wait);
}
savedThis = this;
savedArgs = arguments;
if (timer) {
debounce.cancel();
setTimer();
} else {
setTimer();
}
}
/**
* Immediately invoke function
*/
debounce.flush = function() {
func.apply(savedThis, savedArgs);
};
/**
* Cancel delayed func invocations
*/
debounce.cancel = function() {
if (timer) {
clearTimeout(timer);
timer = null;
}
};
return debounce;
};
}(typeof exports === 'undifined' ? this['td']={} : exports));