Sobes.tech
Junior — Middle

Have you had practical experience using the debounce method in your projects?

sobes.tech AI

Answer from AI

Yes, I often use the debounce method to optimize event handling that can trigger too frequently, such as when typing in a search box or resizing a window. It delays the execution of a function until a series of rapid calls stops, reducing load and preventing unnecessary operations.

Example of debounce in JavaScript:

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

const onResize = debounce(() => {
  console.log('Window resized');
}, 300);

window.addEventListener('resize', onResize);

In this example, the onResize function will only be called after the user stops resizing the window for 300 ms.