JavaScript - Debouncing and Throttling in JavaScript

 

Debouncing and throttling are techniques used to control how often a function is executed, especially when dealing with events that can fire many times in a short period. Examples include scrolling, resizing the window, typing in a search box, or mouse movement. These techniques improve performance and prevent unnecessary repeated function calls.

Debouncing

Debouncing ensures that a function is executed only after a certain amount of time has passed since the last event occurred. If the event keeps occurring, the timer keeps resetting. The function runs only when the event stops for the specified delay.

Example: When a user types in a search box, instead of sending a request for every key press, the system waits until the user stops typing for a short time before making the request.

Example code:

function debounce(func, delay) {
    let timer;
    return function() {
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(this, arguments);
        }, delay);
    };
}

function searchData() {
    console.log("Searching...");
}

let debouncedSearch = debounce(searchData, 500);

In this example, the search function will run only after the user stops typing for 500 milliseconds.

Throttling

Throttling ensures that a function is executed at most once in a specified time interval, no matter how many times the event occurs. This means the function will run regularly but with a fixed time gap between each execution.

Example: When tracking the scroll position of a webpage, you may want the function to run only once every 200 milliseconds rather than on every scroll event.

Example code:

function throttle(func, limit) {
    let inThrottle;
    return function() {
        if (!inThrottle) {
            func.apply(this, arguments);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

function handleScroll() {
    console.log("Scroll event handled");
}

let throttledScroll = throttle(handleScroll, 200);

In this example, the scroll handler will run only once every 200 milliseconds, even if the user scrolls continuously.

Difference Between Debouncing and Throttling

Debouncing delays the execution until the event stops occurring for a specified time. Throttling limits the number of times a function can run within a specific time interval.

Debouncing is commonly used in search inputs and form validation. Throttling is commonly used in scroll tracking, resizing events, and performance monitoring where regular updates are needed but not too frequently.