Debounce and Throttle Functions
# Debounce and Throttle Functions
Both debounce and throttle are used to prevent a function from being called multiple times during high-frequency events. They are performance optimization techniques.
The difference is that a debounce function will only call the function once, n milliseconds after the high-frequency events have stopped, whereas a throttle function will call the function once every n milliseconds during the high-frequency events.
# Debounce Function
After a high-frequency event is triggered, the function will only execute once after a specified delay (wait). If the high-frequency event is triggered again within the specified time (wait), the timer is reset.
# Implementation
// Debounce function
function debounce(func, wait) {
let timeout = null;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
2
3
4
5
6
7
8
9
10
11
12
# Throttle Function
Within a given unit of time, the function can only be triggered once. If the function is triggered multiple times within this time window, only one call takes effect.
# Implementation
// Throttle function
function throttle(func, wait) {
let timeout = null;
return function () {
let context = this;
let args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
# Use Cases
Common use cases involve calling functions during high-frequency events, such as the window object's resize and scroll events, mousemove during drag operations, and keyup events for text input and auto-completion.
# Debounce Use Cases
- Scroll event triggering
- Search input queries -- if the user is still typing, there is no need to keep calling the server API. Wait until the user stops typing, then call. Setting an appropriate time interval effectively reduces server load.
- Form validation
- Button submit events
- Browser window resizing -- resize events (e.g., recalculate layout after the window stops resizing)
# Throttle Use Cases
- DOM element drag functionality (mousemove)
- Search suggestions (keyup)
- Calculating mouse movement distance (mousemove)
- Canvas drawing board functionality (mousemove)
- Shooting game mousedown/keydown events (only one bullet can be fired per time unit)
- Listening for scroll events to determine if the page has reached the bottom for auto-loading more content
# Example
See the Pen Debounce and Throttle Functions by xugaoyi (@xugaoyi) on CodePen.