Understanding Debounce and Throttle Functions in JavaScript

Debounce Function

The debounce function delays the execution of a function until a certain time has passed since the last time the event was triggered. If the event is triggered frequently, the function execution will be postponed, and only when there is a pause in the event triggering, the function will be executed.

Application Scenarios of Debounce Function:

  • Input fields with frequent user input, like search or submit operations.
  • Frequent button clicks that trigger certain actions.
  • Listening to scroll events on a webpage for specific operations.
  • Handling browser resize events more efficiently.

Debounce Function Example:

function myDebounce(fn, delay) {
  let timer = null;

  const debounceFn = function() {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  };

  return debounceFn;
}

// Usage example:
const inputEl = document.querySelector("input");
let count = 0;

const inputChange = function() {
  count++;
  console.log("Sending network request", count, this.value);
};

// Implement debounce
inputEl.oninput = myDebounce(inputChange, 1000);

Throttle Function

The throttle function executes a function at a regular interval. It ensures that, regardless of how many times the event is triggered within the interval, the function is executed only once during that interval.

Application Scenarios of Throttle Function:

  • Limiting the execution of a function when handling frequent user interactions, like button clicks.
  • Handling events related to mouse movement or scroll in a controlled manner.

Throttle Function Example:

function myThrottle(fn, interval) {
  let lastTime = 0;

  const throttleFn = function() {
    const nowTime = new Date().getTime();
    const waitTime = interval - (nowTime - lastTime);

    if (waitTime <= 0) {
      fn.apply(this, arguments);
      lastTime = nowTime;
    }
  };

  return throttleFn;
}

// Usage example:
const buttonEl = document.querySelector("button");
let count = 0;

const throttleFn = function(event) {
  count++;
  console.log("Response count", count, this, event);
};

// Implement throttle
buttonEl.onclick = myThrottle(throttleFn, 1000);

Optimization for Debounce and Throttle Functions

  1. Binding this context: To ensure the correct this context within the debounced or throttled function, use apply or call when invoking the original function.
  2. Passing additional arguments: To pass additional arguments to the debounced or throttled function, spread the arguments object or pass them directly when invoking the original function.
  3. Immediate (first-time) execution: To execute the function immediately on the first event, use an additional parameter (e.g., immediate) in the debounce or throttle function. If immediate is true, the function will be executed immediately on the first event.

These debounce and throttle functions can help optimize performance and improve the user experience in various scenarios, especially when handling frequent user interactions and reducing unnecessary function calls.

Guess you like

Origin blog.csdn.net/weixin_60895836/article/details/131982754