debounce resize in javascript

One way to debounce the resize event in JavaScript is to use a debounce function that delays the execution of a function until a certain amount of time has passed without the event being triggered again.

Here's an example function:

index.tsx
function debounce(func, delay) {
  let timerId;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timerId);
    timerId = setTimeout(function() {
      func.apply(context, args);
    }, delay);
  }
}
243 chars
12 lines

To use this function to debounce the resize event on the window object, you can attach an event listener and pass in the debounced function as the event handler:

index.tsx
window.addEventListener('resize', debounce(function() {
  console.log('Window was resized');
}, 300));
103 chars
4 lines

In this example, the console.log statement will only be executed 300 milliseconds after the resize event stops firing. This can help improve performance by reducing the number of unnecessary recomputations caused by rapid resizing.

gistlibby LogSnag