-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
64 lines (58 loc) · 2.06 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
/**
* @fileoverview Debouncing and throttling library optimizes event handling by
* delaying or limiting function execution.
*
* @see https://google.github.io/styleguide/javascriptguide.xml
* @see https://developers.google.com/closure/compiler/docs/js-for-compiler
* @see https://github.com/Datamart/Glize
* @module debouncing
*/
/**
* In the debouncing technique, no matter how many times the user fires the
* event, the attached function will be executed only after the specified
* time once the user stops firing the event.
*
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds.
* @param {!Function} func The function to execute.
* @param {number=} timeout The timeout in milliseconds. Default 250 ms.
* @return {!Function} Returns a function, that, as long as it continues
* to be invoked, will not be triggered.
* @see https://davidwalsh.name/javascript-debounce-function
* @method
*/
export const debounce = (func, timeout = 250) => {
let /** ?number */ timer;
return (...args) => {
const deferred = () => {
timer = null;
func(...args);
};
timer && clearTimeout(timer);
timer = setTimeout(deferred, timeout);
};
};
/**
* Throttling is a technique in which, no matter how many times the user
* fires the event, the attached function will be executed only once in a
* given time interval.
*
* Returns a function, that, as long as it continues to be invoked, will only
* trigger every N milliseconds.
* @param {!Function} func The function to execute.
* @param {number=} timeout The timeout in milliseconds. Default 250 ms.
* @return {!Function} Returns a function, that, as long as it continues
* to be invoked, will only trigger every N milliseconds.
* @method
*/
export const throttle = (func, timeout = 250) => {
let /** ?number */ timer;
return (...args) => {
const deferred = () => {
timer = null;
func(...args);
};
if (!timer) timer = setTimeout(deferred, timeout);
};
};