Sobes.tech
Middle

What is debounce? Write a debounce function without using libraries in vanilla JS.

sobes.tech AI

Answer from AI

Debounce is a programming technique that limits the frequency of function calls. If a function is called frequently (for example, during text input or scrolling), debounce ensures that it only executes after a certain amount of time has passed since the last call.

This is useful for optimizing performance and preventing redundant operations.

Example of a debounce function in vanilla JS:

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

// Usage:
const handleResize = debounce(() => {
  console.log('Window resized');
}, 300);

window.addEventListener('resize', handleResize);

In this example, handleResize will be called no more than once every 300 milliseconds after the last resize event.

What is debounce? Write a debounce function without… - sobes.tech