HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Debounce a JavaScript function

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptdebouncefunction

Problem

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.
@You might also like

Solution

const debounce = (fn, ms = 0) => {
  let timeoutId;

  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), ms);
  };
};

window.addEventListener(
  'resize',
  debounce(() => {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
  }, 250)
); // Will log the window dimensions at most every 250ms


@You might also like

Code Snippets

const debounce = (fn, ms = 0) => {
  let timeoutId;

  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), ms);
  };
};

window.addEventListener(
  'resize',
  debounce(() => {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
  }, 250)
); // Will log the window dimensions at most every 250ms

Context

From 30-seconds-of-code: debounce-function

Revisions (0)

No revisions yet.