2020-06-01

debounce & throttle

Disclaimer

This article is originally based on my understanding of this concept. No guarantee on the accuracy.😅

Throttle

throttle

Throttle is used to limit how often a function can be called, though throttle is simpler to implement

Using a flag to record the state: within or exceed the time limit

Use case: during scrolling, resizing

1
2
3
4
5
6
7
8
9
10
11
12
13
const throttle = (fn, limit) => {
let flag = false; //init the flag
return (...arg) => {
if (!flag) { //if the flag is false, exceeds the limit
fn(arg); //run the passed in function
flag = true; //turn the flog to ture, still inside the limit
setTimeout(() => { //use a timer to turn flag to false after the limit
flag = false;
}, limit);
}
//if the flag was true, do nothing.
};
};

Debounce

debounce

A debounced function is called only once in a given period, delay milliseconds after its last invocation (the timer is reset on every call).

use case: auto search

1
2
3
4
5
6
7
8
9
const debounce = (fn, limit) => {
let id;
return (...arg) => {
if (id) clearTimeout(id); //every time the function was called, test if the the timer is running, if so, restart the timer
id = setTimeout(() => {
fn(arg);
}, limit);
};
};