Skip to content

Library: debounce()

Eugene Lazutkin edited this page Jul 11, 2018 · 4 revisions

debounce() module is a function, which collects calls to a controlled function within a time window, then calls it with the last arguments. A function is guaranteed to be called within a given time window from the first call. All subsequent calls within the time window will override arguments. The last arguments will be used in the call.

Usually, this is the most useful function to reduce numbers of calls when processing user input. Unlike delay() it provides intermediate updates. Unlike throttle() it doesn't call immediately allowing an opportunity to correct possible input mistakes.

The definition is trivial:

const debounce = (f, ms = 50) => {
  let handle, savedArgs;
  return (...args) => {
    savedArgs = args;
    if (!handle) {
      handle = setTimeout(() => {
        const args = savedArgs;
        handle = savedArgs = null;
        f(...args);
      }, ms);
    }
  };
};

Usage

In a module-enabled environment (like Babel) it can be accessed like that:

import debounce from '@researchnow/reno/src/utils/debounce';

In global-based environments (like a browser) it is frequently mapped to Reno.utils.debounce.

debounce(f, ms=50)

The function takes the following arguments:

  • f is a controlled function. The access to this function is going to be debounced. It can take any number of arguments but its return value will be ignored.
  • ms is a positive integer, which specifies a debounce time window in milliseconds.

Examples

Do a service call when a user has finished entering data but no frequently than once per 750 milliseconds:

const doServiceCall = debounce(serviceCall, 750);

// ...

input.addEventListener('input', evt => doServiceCall(evt.target.value));

Clone this wiki locally