Design & Download
Your JS Library
in Seconds!!!

Snippet: throttle()

Written by Christopher West (cwest) on January 29, 2016.
Creates a throttled version of a function which will only be executable once per every specified wait period.
function throttle(fn, msBetweenCalls, opt_leading) {
  var lastTimeCalled = 0,
      objThis,
      args,
      result,
      timeoutID,
      leading = opt_leading,
      trailing = opt_leading != undefined && !opt_leading;
  function fnThrottled() {
    lastTimeCalled = new Date;
    clearTimeout(timeoutID);
    timeoutID = null;
    result = fn.apply(objThis, args);
  }
  return function() {
    var now = new Date,
        msTilAllowed = msBetweenCalls - (now - lastTimeCalled);
    objThis = this;
    args = arguments;
    if (trailing && msTilAllowed <= 0) {
      msTilAllowed = msBetweenCalls;
    }
    msTilAllowed > 0
      ? leading || timeoutID || (timeoutID = setTimeout(fnThrottled, msTilAllowed))
      : fnThrottled();
    return result;
  };
}

throttle(...) API Documentation

Creates a throttled version of a function which will only be executable once per every specified wait period.

Parameters

  1. fn {Function}:
    The function which will esentially be rate-limited.
  2. msBetweenCalls {number}:
    The amount of time to wait between calls.
  3. opt_leading {boolean}:
    Optional. Indicates whether or not the leading call or the trailing call should be executed. If false the trailing call will be made. If true the leading call will be made.

Returns

The throttled version of fn function.