Debounce and Throttle

Debounce enforces that a function not be called again until a certain amount of time has passed without it being called.
Throttle enforces a maximum number of times a function can be called over time.

Debounce

There are two kinds of debounce: non-immediate execution and immediate execution.

non-immediate execution

It means the function won’t be invoked immediately, but n seconds later. If the function was called in the waiting period, the timer will be reset.

1
2
3
4
5
6
7
8
9
10
11
12
13
const debounce = (func, delay) => {
let timeout;
return function() {
const context = this;
const args = arguments;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
func.apply(context, args)
}, delay);
}
}

immediate execution

It means the function will be invoked immediately, but it will continue until no more called in n seconds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const debounce = (func, delay) => {
let timeout;
return function() {
const context = this;
const args = arguments;
if (timeout) {
clearTimeout(timeout);
}
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, delay);
if (callNow) {
func.apply(context, args);
}
};
};

Throttle

Date.now()

1
2
3
4
5
6
7
8
9
10
11
12
const throttle = (func, delay) => {
let pre = 0;
return function() {
const context = this;
const args = arguments;
let now = +new Date();
if (now - pre >= delay) {
func.apply(context, args);
pre = now
}
};
};

setTimeout()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const throttle = (func, delay) => {
let timeout;
let pre = 0;
return function() {
const context = this;
const args = arguments;
if (!timeout) {
timeout = setTimeout(function() {
timeout = null;
func.apply(context, args);
}, delay);
}
};
};

Use cases

Debounce:

  • search association
  • window resize

Throttle:

  • click mouse continually
  • listen scroll event

References

https://juejin.im/post/5b651dc15188251aa30c8669
https://juejin.im/post/5b8de829f265da43623c4261