Skip to content

Debounce vs Throttle

Debounce and Throttle functions are two useful techniques to limit how often to run a certain function.

Debounce

Wait for N amount of time since the last time the function was invoked. Anytime the function is invoked the wait time resets.

Example: autocomplete search bar will debounce the search until the user finishes typing. If the typing continuous, the wait continues.

The Lodash library contains useful functions to make any function into a debounced function: i.e.

js
import _ from "lodash";

// the "search" function will only call after "searchDebounced" has not been invoked in 300ms
const searchDebounced = _.debounce(search, 300, {
	'leading': true,
	'trailing': true
})

Throttle

Limit the number of calls to a function to every N amount of time.

Example: Throttle update button that sends a PUT API request so that we don't create too many network calls but we still get the latest update.

Similarly, Lodash includes a throttle function to make any function throttled

js
import _ from "lodash";

// The "update" function will only be called at most once every 300ms
const updateThrottled = _.throttle(update, 300);