Source

debounce.js

/**
 * debounce
 *
 * @since 1.3.0
 * @author caiyue;
 * @param func {function}
 * @param wait {number}
 *
 * @example
 *
 * var debounced = debounce(()=>{console.log(123)}, 500);
 * //cancel the debounce function
 * debounced.cancel();
 */

const debounce = (func, wait) => {
  if (typeof func !== 'function') {
    throw new TypeError('Expected a function');
  }
  let timerId;

  function cancel() {
    clearTimeout(timerId);
  }

  function debounced() {
    if (timerId) {
      cancel();
    }
    timerId = setTimeout(func, wait);
  }

  debounced.cancel = cancel;
  return debounced;
};
export default debounce;