JavaScript Throttle and Debounce

JavaScript Throttle and Debounce

Throttle

In software development, particularly in the context of APIs or network requests, a throttle is a mechanism used to limit the rate at which requests or actions can be made.
When you want an event to happen only once in an interval & only the first event is used.

Understand Code

function throttleFn(innerFn, delay) {
    let wait = false;
    return function (...args) {
        if (wait) {
            console.log('waiting stage, cannot process further events.');
            return;
        }
        innerFn(...args);
        wait = true;
        setTimeout(() => {
            wait = false;
            console.log('wait over, I am ready to process new event');
        }, delay);
    }
}

– Throttle function takes two arguments, first is function and second is a delay time.
– It returns a function, which means it forms a Closure.
– Inner function takes arguments that are required to execute callback.
– Now run the passed function and set the wait variable as true.
– Apply a check for the wait variable and if it is true then stop next all calling the same event.
– Mark this wait variable to false inside settimeout web API with passed delay time.
– And once it becomes false, it is ready to take the next event.

Example – User can apply the coupon one time only in a specific time interval.

let productValue = 100;

function apply20Coupon(discount) {
    console.log("New price", productValue - (productValue * discount) / 100);
}

// coupon function is first parameter and timer is second parameter.
const fn = throttleFn(apply20Coupon, 2000);

fn(20); // will print new price

setTimeout(() => {
    fn(20); // waiting stage, cannot process further events.
}, 1000);

setTimeout(() => {
    fn(20); // waiting stage, cannot process further events. // wait over, I am ready to process new event
}, 1500);

setTimeout(() => {
    fn(30); // will print new price
}, 2000);

Another Example of Throttle – Request limits how frequently the fetch method can be called to avoid overloading the server.

Debounce

Debouncing is another useful technique in programming, particularly in scenarios where you want to handle events that may be triggered rapidly, such as keyboard input or scroll events. Debouncing ensures that a function is only executed after a certain amount of time has passed since the last invocation of the function.

function debounce(fn, delay) {
    let timerId = null;
    return function (...args) {
        if (timerId) {
            clearInterval(timerId);
        }
        timerId = setTimeout(() => {
            fn(...args);
        }, delay);
    }
}

– Debounce function makes sure that your code is only triggered once per user input.
– Debounce limits the rate at which a function gets invoked.
– It ensures that time-consuming tasks do not fire so often.
– When we want to limit the keystrokes for which We have to call some action.

In simple words Debounce is When we have an event or API calling on every key press or user input, then it hits that event only when the User stops typing.

Use of debouncing method –


function printHello() {
    const d = new Date();
    console.log("hello, I am debouncing, time is - ", d.getMilliseconds());
}
const debouncedPrintHello = debounce(printHello, 1000);

// Here we are firing events constantly so only last one will be fired, rest all will be ignored.
debouncedPrintHello();
debouncedPrintHello();
debouncedPrintHello();

// This event is fired after some delay so it will consider.
setTimeout(() => {
    debouncedPrintHello();
}, 1000);

Difference between Debounce & Throttle –  

Debounce process last event and Throttle process first event.

Debounce waits till the User stops providing input & then hits the event, Throttle first hits the event and then waits till the provided wait period.

JavaScript Throttle and Debounce