throttle source npm

_.throttle(func, [wait=0], [options])

Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled function comes with a cancel method to cancel delayed invocations. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to the throttled function return the result of the last func call.

Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if the the throttled function is invoked more than once during the wait timeout.

See David Corbacho's article for details over the differences between _.throttle and _.debounce.

Arguments

  1. func (Function)

    The function to throttle.

  2. [wait=0] (number)

    The number of milliseconds to throttle invocations to.

  3. [options] (Object)

    The options object.

  4. [options.leading=true] (boolean)

    Specify invoking on the leading edge of the timeout.

  5. [options.trailing=true] (boolean)

    Specify invoking on the trailing edge of the timeout.

Returns (Function)

Returns the new throttled function.

Example

// avoid excessively updating the position while scrolling
jQuery(window).on('scroll', _.throttle(updatePosition, 100));

// invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
  'trailing': false
}));

// cancel a trailing throttled call
jQuery(window).on('popstate', throttled.cancel);