What are Debouncing and Throttling in JavaScript and How to Use?

Debounce and throttle are two fundamental techniques in JavaScript for managing the execution of functions, particularly in situations involving frequent and potentially expensive function calls. They are often used to improve performance and user experience, especially when dealing with events like scrolling, resizing, or typing.

Debounce: Delayed Execution

Debouncing is a technique used to ensure that a function is not called too frequently. It’s typically used in scenarios where you want to wait for some time after the last event before taking an action.

This is useful when you’re dealing with events that can fire rapidly (such as scrolling or keyboard input) but you only want to respond to the final event after a certain delay.

Here’s a basic implementation of debouncing in JavaScript:

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

// Run after 3 seocnds or (3000 milliseconds)
const runAfter3Seconds = debounce(function (name) {
    console.log("Hi, " + name);
}, 3000);

runAfter3Seconds("Babu Rao");

You can use this debounce function to wrap any function you want to debounce:

Use Cases for Debounce:

Throttle: Rate-Limited Execution

Throttling is a technique used to ensure that a function is not called more often than a certain time interval.

Unlike debouncing, where the function is delayed until after the last event, throttling guarantees that the function is only executed at most once per specified interval.

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

// call once every 3 seconds
const sayHi = throttle(function () {
    console.log("Hi");
}, 3000);

// Call sayHi() every second:
setInterval(() => {
    sayHi(); //This function will run once in 3 seconds
}, 1000);

Use Cases for Throttle:

Debounce vs. Throttle: When to Use Which

The choice between debounce and throttle depends on the specific use case and the desired behavior: