Sha256: ee7f3a04d27a23ba087aed63eab418c540510fc5c313ea04e3dd821b878150c4

Contents?: true

Size: 1.72 KB

Versions: 6

Compression:

Stored size: 1.72 KB

Contents

/**
 * Returns a function, that, as long as it continues to be invoked, will not
 * be triggered. The function will be called after it stops being called for
 * N milliseconds. If `immediate` is passed, trigger the function on the
 * leading edge, instead of the trailing. The function also has a property 'clear' 
 * that is a function which will clear the timer to prevent previously scheduled executions. 
 *
 * @source underscore.js
 * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
 * @param {Function} function to wrap
 * @param {Number} timeout in ms (`100`)
 * @param {Boolean} whether to execute at the beginning (`false`)
 * @api public
 */
export default function debounce(func, wait, immediate){
  var timeout, args, context, timestamp, result;
  if (null == wait) wait = 100;

  function later() {
    var last = Date.now() - timestamp;

    if (last < wait && last >= 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      if (!immediate) {
        result = func.apply(context, args);
        context = args = null;
      }
    }
  };

  var debounced = function(){
    context = this;
    args = arguments;
    timestamp = Date.now();
    var callNow = immediate && !timeout;
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };

  debounced.clear = function() {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
  };
  
  debounced.flush = function() {
    if (timeout) {
      result = func.apply(context, args);
      context = args = null;
      
      clearTimeout(timeout);
      timeout = null;
    }
  };

  return debounced;
};

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
spina-2.18.0 app/assets/javascripts/spina/libraries/debounce.js
spina-2.17.0 app/assets/javascripts/spina/libraries/debounce.js
spina-2.16.0 app/assets/javascripts/spina/libraries/debounce.js
spina-2.15.1 app/assets/javascripts/spina/libraries/debounce.js
spina-2.15.0 app/assets/javascripts/spina/libraries/debounce.js
spina-2.14.0 app/assets/javascripts/spina/libraries/debounce.js