CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-lodash-throttle

The lodash method `_.throttle` exported as a module.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Lodash Throttle

Lodash Throttle provides the _.throttle method as a standalone npm module for rate-limiting function calls. It creates throttled functions that only invoke the original function at most once per specified wait period, with configurable leading and trailing edge execution control.

Package Information

  • Package Name: lodash.throttle
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install lodash.throttle

Core Imports

var throttle = require('lodash.throttle');

For ES modules environments:

import throttle from 'lodash.throttle';

Basic Usage

var throttle = require('lodash.throttle');

// Basic throttling - limits function calls to once per 100ms
var throttledUpdate = throttle(function(value) {
  console.log('Update called with:', value);
}, 100);

// Call multiple times quickly - only executes once per 100ms
throttledUpdate('a');
throttledUpdate('b'); 
throttledUpdate('c');

// With options for leading/trailing edge control
var scrollHandler = throttle(updatePosition, 100, {
  leading: true,
  trailing: false
});

window.addEventListener('scroll', scrollHandler);

// Cancel pending invocations
scrollHandler.cancel();

// Immediately execute pending invocation
scrollHandler.flush();

Architecture

Lodash Throttle is built on top of the debounce implementation with specific configuration to create true throttling behavior:

  • Internal Implementation: Uses debounce with maxWait set equal to the wait parameter, ensuring function execution at least once per wait period
  • Edge Control: Configurable leading and trailing edge execution through options
  • Timer Management: Maintains internal timer state with automatic cleanup and reset mechanisms
  • Method Attachment: Dynamically attaches cancel and flush control methods to the returned throttled function
  • Argument Preservation: Preserves the most recent arguments and this context for delayed invocations

Capabilities

Throttle Function

Creates a throttled function that only invokes the provided function at most once per every wait milliseconds.

/**
 * Creates a throttled function that only invokes `func` at most once per
 * every `wait` milliseconds.
 * @param {Function} func The function to throttle.
 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
 * @param {Object} [options={}] The options object.
 * @param {boolean} [options.leading=true] Specify invoking on the leading edge of the timeout.
 * @param {boolean} [options.trailing=true] Specify invoking on the trailing edge of the timeout.
 * @returns {Function} Returns the new throttled function.
 */
function throttle(func, wait, options);

Parameters:

  • func (Function): The function to throttle
  • wait (number, optional): The number of milliseconds to throttle invocations to. Defaults to 0
  • options (Object, optional): The options object with the following properties:
    • leading (boolean, optional): Specify invoking on the leading edge of the timeout. Defaults to true
    • trailing (boolean, optional): Specify invoking on the trailing edge of the timeout. Defaults to true

Returns: Function - The new throttled function with attached cancel and flush methods

Usage Examples:

var throttle = require('lodash.throttle');

// Throttle scroll events to improve performance
var onScroll = throttle(function() {
  console.log('Scroll event processed');
}, 100);

window.addEventListener('scroll', onScroll);

// Throttle API calls - only leading edge execution
var saveData = throttle(function(data) {
  api.save(data);
}, 1000, { trailing: false });

// Throttle with both leading and trailing execution (default behavior)
var updatePosition = throttle(function(x, y) {
  element.style.left = x + 'px';
  element.style.top = y + 'px';
}, 50);

Cancel Method

Cancels delayed function invocations.

/**
 * Cancels delayed function invocations
 * @returns {void}
 */
throttledFunction.cancel();

The cancel method is attached to every throttled function returned by throttle(). It clears any pending invocations that would have been executed on the trailing edge.

Usage Example:

var throttled = throttle(expensiveOperation, 1000);

// Queue some calls
throttled();
throttled();

// Cancel any pending trailing execution
throttled.cancel();

Flush Method

Immediately invokes pending function invocations.

/**
 * Immediately invokes pending function invocations
 * @returns {*} Returns the result of the last func invocation
 */
throttledFunction.flush();

The flush method is attached to every throttled function returned by throttle(). It immediately executes any pending invocation that would have been executed on the trailing edge.

Usage Example:

var result;
var throttled = throttle(function(value) {
  result = value * 2;
  return result;
}, 1000);

throttled(5);
throttled(10);

// Immediately execute with the last arguments (10)
var flushResult = throttled.flush();
console.log(flushResult); // 20
console.log(result); // 20

Types

/**
 * Options object for throttle function
 */
interface ThrottleOptions {
  /** Specify invoking on the leading edge of the timeout */
  leading?: boolean;
  /** Specify invoking on the trailing edge of the timeout */
  trailing?: boolean;
}

/**
 * Throttled function with cancel and flush methods
 */
interface ThrottledFunction<T extends (...args: any[]) => any> {
  /** Call the throttled function */
  (...args: Parameters<T>): ReturnType<T>;
  /** Cancel delayed function invocations */
  cancel(): void;
  /** Immediately invoke pending function invocations */
  flush(): ReturnType<T>;
}

Error Handling

The throttle function throws a TypeError if the first argument is not a function:

try {
  var invalid = throttle('not a function', 100);
} catch (error) {
  console.log(error.message); // "Expected a function"
}

Performance Considerations

  • Leading vs Trailing: Use leading: true, trailing: false for immediate response to user input
  • Trailing only: Use leading: false, trailing: true for batching operations
  • Wait time: Choose appropriate wait times based on use case:
    • UI events (scroll, resize): 16-100ms
    • API calls: 300-1000ms
    • User input validation: 300-500ms

Common Use Cases

var throttle = require('lodash.throttle');

// 1. Scroll event optimization
var onScroll = throttle(function() {
  updateScrollPosition();
}, 16); // ~60fps

// 2. Window resize handling
var onResize = throttle(function() {
  recalculateLayout();
}, 100);

// 3. API request rate limiting
var searchAPI = throttle(function(query) {
  fetch('/api/search?q=' + query)
    .then(handleResults);
}, 300, { leading: false });

// 4. Mouse move tracking with immediate feedback
var onMouseMove = throttle(function(event) {
  updateCursor(event.clientX, event.clientY);
}, 16, { trailing: false });
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/lodash.throttle@4.1.x
Publish Source
CLI
Badge
tessl/npm-lodash-throttle badge