Debouncing & Throttling in JavaScript

Debouncing & Throttling in JavaScript

Debouncing and throttling are techniques in javascript to optimise the application and browser performance.

Understanding Debounce in JavaScript:

In JavaScript, debouncing groups multiple sequential calls to a function into one call to prevent multiple notifications for a single event. Its implementation is straightforward, following a simple logic.

  1. Establish a timer variable to regulate when the callback function should execute.

  2. Reset this timer function each time a user initiates an action.

The code below demonstrates this logic:

let debounceTimer;

const debounce = (callback, time) => {
  window.clearTimeout(debounceTimer);
  debounceTimer = window.setTimeout(callback, time);
}

In this codе snippеt, thе dеbouncе function utilizеs a timеr variablе (dеbouncеTimеr) to control thе invocation of a providеd callback function aftеr a spеcifiеd timе intеrval. It еnsurеs that thе callback function rеmains inactivе until thе timеr has еlapsеd. This mеchanism provеs еspеcially valuablе whеn intеgratеd into еvеnt listеnеrs, such as scroll еvеnts, whеrе thе timеr rеsеts еvеry timе thе usеr intеracts.

Practical Applications of Dеbouncing:

Dеbouncing provеs invaluablе for managing еvеnts dеpеndеnt on sporadic usеr intеractions, such as typing into an input fiеld or clicking a button. For instancе, whеn dеsigning a sеarch bar that initiatеs API calls basеd on usеr input, implеmеnting a dеbouncе function can significantly rеducе thе frеquеncy of API rеquеsts.

In thе following еxamplе, usеr input is dеbouncеd to rеturn thе input valuе only if thе usеr rеfrains from typing for 500 millisеconds:

let input = document.getElementById('name');
let debounceValue = document.getElementById('debounce-value');

const updateDebounceValue = () => {
  debounceValue.innerHTML = input.value;
}

let debounceTimer;

const debounce = (callback, time) => {
  window.clearTimeout(debounceTimer);
  debounceTimer = window.setTimeout(callback, time);
};

input.addEventListener(
  "input",
  () => {
    debounce(updateDebounceValue, 500)
  },
  false
);

This practical application showcases how debouncing can enhance the user experience by optimizing the handling of user-driven events.

Understanding throttle in JavaScript:

We can think of throttle as a minimizing function; it minimizes the number of calls made within a certain time interval.

Defining the logic for a throttle, we have:

  1. Initialize a variable to detect if the function has been called within the specified time

  2. If the function has been called, pause the throttle function

  3. If the function hasn’t been called or is done running in the interval, rerun the throttle function

We can write this in JavaScript as:

//initialize throttlePause variable outside throttle function 
let throttlePause;
const throttle = (callback, time) => {
  //don't run the function if throttlePause is true 
  if (throttlePause) return;
  //set throttlePause to true after the if condition. This allows the function to be run once 
  throttlePause = true;

  //setTimeout runs the callback within the specified time 
  setTimeout(() => {
    callback();

    //throttlePause is set to false once the function has been called, allowing the throttle function to loop 
    throttlePause = false;
  }, time);
};

Here is a step-by-step explanation of the process:

  1. Initially, throttlePause is undefined, so the function proceeds to the next line.

  2. We then set throttlePause to true for the next iteration. If the throttle function is called again before setTimer finishes, the function will return undefined.

  3. setTimeout initiates a timer to run the function. This timer runs asynchronously while the throttle function is being called, so it will not be affected by the throttle function being called again.

  4. After the callback has been executed, throttlePause is set to false so that the throttle function can continue to loop.

Use Cases for Throttle:

If you're scrolling or resizing, throttle can come in handy. Throttle allows you to control how often your scroll handler is called, making it useful for animating elements based on their scroll position or managing an infinite scroll page.
In my personal portfolio, I utilize throttle.

exemple code :

let throttleTimer;
const throttle = (callback, time) => {
  if (throttleTimer) return;
    throttleTimer = true;
    setTimeout(() => {
        callback();
        throttleTimer = false;
    }, time);
}
window.addEventListener("scroll", () => { 
  throttle(ScrollwithThrottle, 250);
});

Summary:

  1. Debouncing is a technique where we can monitor the time delay of user action and once that delay reaches our predetermined threshold we can can make the function call.

  2. Throttling is a technique where we will delay executing a function. It will reduce the notifications of an event that fires multiple times.

  3. Although debouncing and throttling may seem similar, they each have their own specific uses. It is not advisable to use throttling for search bars, just as it would not be appropriate to use debouncing for activities such as browser resizing, or onScroll events.

    You can visually see the difference here
    resource: geeksforgeeks