What is Throttling and Debouncing?

Throttling and debouncing are techniques used to regulate or control the rate at which a function is executed. This is to ensure the system is not overwhelmed when a function is repeatedly executed.

Scenarios where throttling or debouncing can be applied are when a function will be called and executed repeatedly due to an event trigger e.g. scroll event, resizing the window, mousemove events, keyboard events, Input events e.t.c.

Difference between throttling and debouncing.

Throttling

There is a set time interval at which a function can be executed only once, and after the execution of the function, it wont be executed a second time within the set time interval. But if the function gets called again when the time interval has already elapsed the function would be executed again.

Applying this to a scroll event example; if for instance a website or an application is to load more content every time the scroll event is triggered that would mean if the event is triggered up to five times within a second then the contents would be loaded five times within a second. A good way to limit the amount of times the contents are loaded within a particular time would be to use a throttle. So if you set your throttle’s time interval to five seconds that would mean irrespective of the amount of times the event is triggered, the function would only be executed once within that five seconds. But if said event gets triggered again after the time interval has already elapsed the function would also be executed again and so on.

// Throttle function accepts a function and time interval as parameters
const throttle = (func, timeInterval) => {
  // Set last call value to zero
  let lastCall = 0;
  //
  return function (...args) {
    // Get the current time the code isbeing executed
    const now = new Date().getTime();

    // Subtract the last call value from the current time 
    // Then compare if it is greater than or equal to time interval
    if (now - lastCall >= timeInterval) {
      func(...args);

      //   Set last call value to now
      lastCall = now;
    }
  };
};

// Set throttle time interval to 5 seconds (5000 milliseconds)
const throttledScrollHandler = throttle(() => {
  // Log time(seconds) when the scroll event triggered execution of the code
  console.log(`New content loaded at ${new Date().getSeconds()} seconds!!!`);
}, 5000);

// Listening for scroll event on the window
window.addEventListener("scroll", throttledScrollHandler);

if you scroll continuously, you will realize that all the logs in the console are 5 seconds apart.

Debouncing

There is a time delay before a function is executed. When an event is triggered there is a delay before the function is executed and if the event gets triggered again within the delay time then it gets reset and starts counting down again.

Applying this to a search suggestions example; If for instance a search input is to show some suggestions after an event like input/keyup/keydown/keypress event is fired, that means every time the user enters a new character into the search input field an event will be fired and the search suggestions function will be executed. But if the function is debounced and a delay time of two seconds is set, when the event is fired the search suggestion function will not be executed until after two seconds has passed, and if the event is triggered again before the two seconds has elapsed the delay time will be reset and the function is not executed until another two seconds has passed from the point of the last event trigger.

// Debounce function accepts a function and delay time as parameters
const debounce = (func, delay) => {
  let timeoutId;

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

// Set debounce delay time to two seconds (2000 milliseconds)
const debounceSearch = debounce((query) => {
    // This would be logged to the console two seconds after the event was fired 
  console.log(`Searching for: "${query}"`);

}, 2000);

// Listen for an input event on the search input field
search.addEventListener("input", (event) => {
  debounceSearch(event.target.value);
});

The debounce function ensures that the search suggestion is made 2 seconds (2000 milliseconds) after the user stops typing.