Throttling vs Debouncing: Are they Same?


Throttling

Throttling limits the execution of a function to at most once in a given period.

Example: The throttle function ensures the onScroll function is called at most once every 2 seconds during scroll events.


function throttle(func, delay) {
    let timerId = null;

    return function () {
        const context = this;
        const args = arguments;

        if (!timerId) {
            func.apply(context, args);
            timerId = setTimeout(() => {
                timerId = null;
            }, delay);
        }
    };
}

function onScroll() {
    console.log("Scroll event fired");
}

const throttledScroll = throttle(onScroll, 2000);
window.addEventListener("scroll", throttledScroll);
    

Debouncing

Debouncing delays the execution of a function until a specified time has passed since the last event.

Example: The debounce function ensures the onInput function is called only if 500 milliseconds have passed since the last input event.


function debounce(func, delay) {
    let timerId;

    return function () {
        const context = this;
        const args = arguments;

        clearTimeout(timerId);
        timerId = setTimeout(() => {
            func.apply(context, args);
        }, delay);
    };
}

function onInput() {
    console.log("Input event fired");
}

const debouncedInput = debounce(onInput, 500);
const inputElement = document.getElementById("searchInput");
inputElement.addEventListener("input", debouncedInput);
    

Usage

Throttling is suitable for situations like handling scroll or resize events where frequent execution is unnecessary and could harm performance.

Debouncing is ideal for scenarios like search inputs, where you want to wait for the user to stop typing before performing an action like fetching search results.

This post provides a clear distinction between throttling and debouncing, along with practical examples of how to implement each technique.

Monir http://monirspace.com

With over thirteen years of professional experience as a Web Developer, I specialize in creating and managing websites and applications for diverse clients. My expertise lies in delivering impactful solutions that meet client needs and drive business objectives.

+ There are no comments

Add yours