JSFiddle - React, Tailwind, and code Playground

by BurpmanJunior

HTML

<div id="throttle">_throttle: 0</div>
<div id="debounce">_debounce: 0</div>
<div id="control">no perf management: 0</div>

JavaScript

/**
 * DEBOUNCE AND THROTTLE
 */

/**
 * Throttle function calls to threshold intervals with optional scope
 * @param  {Function} fn         Function to throttle
 * @param  {Number}   threshhold Threshold in ms
 * @param  {Object}   scope      Scope of function
 * @return {Function}            Fired function
 */
function _throttle(fn, threshhold, scope){
  // Threshhold defaults
  threshhold || (threshhold = 16);
  // Init vars
  var last,
      deferTimer;
      
  // Run
  return function(){
    // Find scope and parse arguments
    var context = scope || this,
        now     = +new Date,
        args    = arguments;

    // Check if still within threshold
    if(last && now < last + threshhold){
      // Defer
      clearTimeout(deferTimer);
      // Defer run to threshold
      deferTimer = setTimeout(function(){
        // Set last
        last = now;
        // Run
        fn.apply(context, args);
      }, threshhold);
    }else{
      // Set last
      last = now;
      // Run
      fn.apply(context, args);
    }
  };
}

/**
 * Debounce function with wait delay, optional leading run and optional scope
 * @param  {Function} fn        Function to debounce
 * @param  {Number}   wait      Delay time in ms
 * @param  {Boolean}  immediate Allow leading edge call
 * @param  {Object}   scope     Scope of function
 * @return {Function}           Fired function
 */
function _debounce(fn, wait, immediate, scope){
  // Init timer
  var timeout;
  // Run
  return function(){
    // Find scope and parse arguments
    var context = scope || this,
        args    = arguments;
    // Run later
    var later = function(){
      timeout = null;
      // Run if trailing
      if(!immediate){
        fn.apply(context, args);
      }
    };
    // Allow immediate if leading and not already running
    var callNow = immediate && !timeout;
    // Clear existing waits
    clearTimeout(timeout);
    // Reset waits
    timeout = setTimeout(later, wait);
    // Run leading
   ...