Debouncing and Throttling Javascript

Debouncing and Throttling are techniques to control the rate of function execution in response to frequent events like scrolling, resizing, or typing.

Debouncing:

function debounce(cb, delay) {
  let timer;

  return (...args) => {
    clearTimeout(timer); // Clear any previously set timer
    timer = setTimeout(() => {
      cb(...args); // Call the function with the latest arguments
    }, delay);
  };
}

function apiCall() {
    console.log("API Call at", new Date().toISOString());
}

const debouncedApiCall = debounce(apiCall, 1000); // Debounce with a 1-second delay

// Simulate frequent calls
debouncedApiCall();
debouncedApiCall();
ebouncedApiCall();

// Only the last call will execute after 1 second

Throttling:

function throttle(cb, time) {
  let lastCall = 0; // Track the last time the callback was executed

  return (...args) => {
    const now = Date.now(); // Current timestamp

    if (now - lastCall >= time) {
      lastCall = now; // Update the last call time
      cb(...args); // Call the function
    }
  };
}

function apiCall() {
    console.log("API Call at", new Date().toISOString());
}

const throttledApiCall = throttle(apiCall, 2000); // Throttle to 1 call per 2 seconds

// Simulate frequent calls
setInterval(() => {
    throttledApiCall();
}, 500); // Attempt to call every 500ms

Summary: