debounce and throttle

by Aleksandr Tomashov

JavaScript

function getUsers(query) {
  console.dir(query);
}

function debounce(f, delay) {
  let timer;
  return function() {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      f.apply(this, arguments);
    }, delay);
  };
}

function throttle(f, delay) {
  let ready = true;
  let arg = null;
  let cont = null;

  return function wrapper(...args) {
    if (!ready) {
      arg = args;
      cont = this;

      return;
    }
    arg = null;
    cont = null;

    f.apply(this, args);
    ready = false;

    setTimeout(() => {
      ready = true;

      if (arg) {
        wrapper.apply(cont, arg);
      }
    }, delay);

  };

}

let getDebounce = debounce(getUsers, 1000);
let getThrottle = throttle(getUsers, 1000);

getThrottle(1);

setTimeout(() => {
  getThrottle(2);
}, 100);

setTimeout(() => {
  getThrottle(3);
}, 200);

setTimeout(() => {
  getThrottle(4);
}, 400);

setTimeout(() => {
  getThrottle(5);
}, 1400);


let input = document.querySelector('input');

input.addEventListener('input', () => {
  getDebounce.call(this, input.value);
});

document.addEventListener('mousemove', (event) => {
  getThrottle(event.clientX);
});