JavaScript Interview Question #122

What is the difference between debouncing and throttling?

Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate

Quick Interview Answer

Debouncing waits until calls stop for a specified delay and then normally runs once. Throttling allows execution at a limited frequency while calls continue.

Detailed Explanation

Debouncing waits until calls stop for a specified delay and then normally runs once. Throttling allows execution at a limited frequency while calls continue.

For example, an autocomplete request is often debounced so it runs after the user pauses typing. A scroll-position update may be throttled so it continues updating during scrolling but not on every browser event.

Code Example

const debouncedSearch = debounce(searchProducts, 300);
input.addEventListener("input", event => {
    debouncedSearch(event.target.value);
});

const throttledScroll = throttle(updatePosition, 100);
window.addEventListener("scroll", throttledScroll);