Skip to content

Library: throttle()

Eugene Lazutkin edited this page Jul 11, 2018 · 1 revision

throttle() module is a function, which makes calls to a controlled function no more than once per a given time window. If several calls are made in a rapid succession only the last call will be made.

Unlike debounce() it does not delay the first call but does it immediately unless we had a previous call within a time window. If calls are relatively rare and spaced more then a time window they all are executed immediately.

The definition is trivial:

const throttle = (f, ms = 50) => {
  let handle,
    savedArgs,
    last = +new Date();
  return (...args) => {
    savedArgs = args;
    if (!handle) {
      const now = +new Date(),
        left = last + ms - now;
      if (left <= 0) {
        const args = savedArgs;
        savedArgs = null;
        last = now;
        f(...args);
      } else {
        handle = setTimeout(() => {
          const args = savedArgs;
          handle = savedArgs = null;
          last = now;
          f(...args);
        }, left);
      }
    }
  };
};

Usage

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

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

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

throttle(f, ms=50)

The function takes the following arguments:

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

Examples

Do a service call updates while a user enters data but no frequently than once per 750 milliseconds:

const doServiceCall = throttle(serviceCall, 750);

// ...

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

Clone this wiki locally