Gyaan

Debouncing and Throttling

intermediate performance events optimization

The major difference between debouncing and throttling is that debounce calls a function when a user hasn’t carried out an event in a specific amount of time, while throttle calls a function at intervals of a specified amount of time while the user is carrying out the event.

For example, if we debounce a scroll function with a timer of 250ms, the function is only called if the user hasn’t scrolled in 250ms. If we throttle a scroll function with a timer of 250ms, the function is called every 250ms while the user is scrolling.

Debounce
Events:
← user stops
Function fires:
only once after pause
Throttle
Events:
Function fires:
at regular intervals

Debouncing

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
);

Throttling

let throttleTimer;

const throttle = (callback, time) => {
  if (throttleTimer) return;
  throttleTimer = true;
  setTimeout(() => {
    callback();
    throttleTimer = false;
  }, time);
}

window.addEventListener("scroll", () => {
  throttle(handleScrollAnimation, 250);
});