-
Notifications
You must be signed in to change notification settings - Fork 1
/
debounce.js
63 lines (51 loc) · 1.46 KB
/
debounce.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
/* DEBOUNCE */
// functionToBeExecuted(); - ignore
// functionToBeExecuted(); - ignore
// functionToBeExecuted(); - ignore
// functionToBeExecuted(); - ignore
// functionToBeExecuted(); - run this one after timeout
function debounce(fn, time) {
let setTimeoutId;
return function() {
// check for existing calls
if(setTimeoutId) {
// reset timer
clearTimeout(setTimeoutId);
}
setTimeoutId = setTimeout( () => {
// invoke fn
fn.apply(this, arguments);
setTimeoutId = null;
}, time)
}
}
/* THROTTLE */
// functionToBeExecuted(); - run this one
// functionToBeExecuted(); - ignore
// functionToBeExecuted(); - ignore
// functionToBeExecuted(); - ignore
// functionToBeExecuted(); - run this one after timeout
function throttle(fn, time) {
let setTimeoutId;
return function() {
if(setTimeoutId) {
return;
}
setTimeoutId = setTimeout( () => {
fn.apply(this, arguments);
setTimeoutId = null;
}, time)
}
}
// https://levelup.gitconnected.com/debounce-in-javascript-improve-your-applications-performance-5b01855e086
const debounce = (func, wait) => {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
}
clearTimeout(timeout);
timeout = setTimeout(later, wait)
}
}