Open In App

Difference between Debouncing and Throttling

Last Updated : 08 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Debouncing: Debouncing is a technique where you delay the execution of a function until after a certain amount of time has passed. This is useful if you have a frequently used function—say, a scroll or resize event listener—and don’t want to trigger it too frequently because that might slow down the browser.

No matter how many times the user fires the event, the connected function will only run once the user stops firing the event, according to the Debouncing approach. Ex: Imagine that a user clicks a button five times in the space of 100 milliseconds. That function won’t be called during debouncing. If the debouncing time is 2000 milliseconds after the user has ceased clicking, the function will be called 2000 milliseconds later.

Advantages: 

  • Decreases the frequency with which a function is invoked, which can enhance performance and avoid pointless effort. 
  • Prevents pointless network and API requests, which can conserve resources and cut expenses.
  • This can be utilized to handle frequent occurrences, such as scrolling or resizing, without taxing the system.

 

Disadvantages: 

  • This may cause a function to take longer to complete, which might be problematic when a quick answer is needed. The result can in missed events if the debounce time is too long.

Implement of Debouncing :

function debounce(func, delay) {
    let timerId;
    return function () {
        const context = this;
        const args = arguments;
        clearTimeout(timerId);
        timerId = setTimeout(function () {
            func.apply(context, args);
        }, delay);
    };
}

Example: In this example, we will use debouncing approach.

Javascript




function delayFuncExec() {
    console.log("I AM GFG ");
}
  
let timerId = setTimeout(delayFuncExec, 1000)
  
console.log("Timer Id: " + timerId);


Output

Timer Id: 2
I AM GFG 

After 100 ms, delayFuncExec will be carried out. The integer produced by the setTimeout method will be stored in timerId.

Throttling: Throttling is a similar technique to debouncing, but instead of delaying the execution of a function, it limits the rate at which a function. This is useful when a function, such as a mousemove or keydown event listener, may be called repeatedly but need not be run each time.

Throttling is a technique in which, no matter how many times the user fires the event, the attached function will be executed only once in a given time interval. Throttling ensures that the function executes at regular intervals.

Advantages:

  • This decreases the frequency of function calls, which can assist in avoiding performance problems and optimizing resource consumption.
  • This is used to restrict the rate at which users enter data using their keyboards or mice in order to stop mistakes or undesirable behaviors.

Disadvantages:

  • Given that the function will only be called at specific intervals, it could not respond right away.
  • If the throttle time is too long, some events can be skipped, which could cause a loss of detail.

Syntax:

function throttle(callback, delay = 1000) {
      let shouldWait = false;
      return (...args) => {
        if (shouldWait) return;
        callback(...args);
        shouldWait = true;
        setTimeout(() => {
              shouldWait = false;
        }, delay);
      };
}

Example: In this example, we will use the throttling approach.

Javascript




function throttle(func, delay) {
    let lastCall = 0;
    return function (...args) {
        const now = new Date().getTime();
        if (now - lastCall < delay) {
            return;
        }
        lastCall = now;
        func(...args);
    };
}
  
function logMessage(message) {
    console.log(message);
}
  
const throttledLogMessage = throttle(logMessage, 1000);
  
// Logs 'Hello'
throttledLogMessage('Hello');
  
// Doesn't log anything
throttledLogMessage('World');
  
// Logs 'Delayed' after 2 seconds
setTimeout(() => throttledLogMessage('Delayed'), 2000);


Output

Hello
Delayed

The throttle function in this example accepts two arguments: func, the function to be throttled, and delay, the minimum interval between calls to func. A new function that encapsulates func and executes the throttling logic is returned by the throttle function. 

Difference between Debouncing and Throttling:

Debouncing

Throttling 

Debouncing waits for a certain time before invoking the function again.

Throttling limits the number of times the function can be called over a certain period.

Ensures that the function is called only once, even if the event is triggered multiple times.

Ensures that the function is called at a regular interval, even if the event is triggered multiple times.

Useful when you want to delay the invocation of a function until a certain period of inactivity has passed.

Useful when you want to list the Frequency of function calls.

Eg. You can debounce an async API request function that is called every time the user types in an input field.

Eg. You can throttle a slide change Function that is called every time the user clicks a button in a carousel.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads