All files / libs debounce.js

100% Statements 13/13
100% Branches 6/6
100% Functions 4/4
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                  11x 27x 10x 10x   27x 27x 27x 27x     11x 2x     11x    
/**
 * Debounce
 * @param {Function} func Function to run.
 * @param {Number} wait Time to wait between tries.
 * @param {Boolean} immediate Immediately call func.
 */
export default function debounce(func, wait, immediate) {
  let timeout;
 
  const debounced = function (...args) {
    const later = () => {
      timeout = null;
      if (!immediate) func.apply(this, args);
    };
    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(this, args);
  };
 
  debounced.clear = function () {
    clearTimeout(timeout);
  };
 
  return debounced;
}