Skip to content

Library: delay()

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

delay() module is a function, which cancels calls to a controlled function within a time window, then restart a timer again. A function will be called after a time window has expired unless another call was made. In this case, the pending call is canceled and a new timer is initialized. Ultimately only the last call will succeed if previous calls canceled each other.

The definition is trivial:

const delay = (f, ms = 50) => {
  let handle, savedArgs;
  return (...args) => {
    savedArgs = args;
    if (handle) {
      clearTimeout(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 delay from '@researchnow/reno/src/utils/delay';

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

delay(f, ms=50)

The function takes the following arguments:

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

Examples

Do a service call only when a user has finished entering data at least for 750 milliseconds:

const doServiceCall = delay(serviceCall, 750);

// ...

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

Clone this wiki locally