Debounce a JavaScript function

JavaScript, Function · Oct 12, 2023

Debouncing is a technique used to limit the number of times a function is called. The function will only be called once, after a specific amount of time has elapsed since its last invocation.

To accomplish this, we can use timeouts to artificially create the necessary delay. Each time the debounced function is invoked, we need to clear the current pending timeout with clearTimeout(). Then, we must use setTimeout() to create a new timeout that delays invoking the function until at least ms milliseconds have elapsed. Finally, using Function.prototype.apply() we can apply the this context to the function and provide the necessary arguments.

const debounce = (fn, ms = 0) => {
  let timeoutId;
  return function(...args) {
    timeoutId = setTimeout(() => fn.apply(this, args), ms);

  debounce(() => {
  }, 250)
); // Will log the window dimensions at most every 250ms

More like this