or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-throttle-debounce

High-performance throttle and debounce utility functions for JavaScript applications

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/throttle-debounce@5.0.x

To install, run

npx @tessl/cli install tessl/npm-throttle-debounce@5.0.0

index.mddocs/

Throttle Debounce

Throttle Debounce provides high-performance throttle and debounce utility functions for JavaScript applications. It offers both throttling (rate-limiting function execution to occur at most once per specified time interval) and debouncing (delaying function execution until after specified time has elapsed since the last invocation) with flexible configuration options.

Package Information

  • Package Name: throttle-debounce
  • Package Type: npm
  • Language: JavaScript (ES modules and CommonJS support)
  • Installation: npm install throttle-debounce

Core Imports

import { throttle, debounce } from "throttle-debounce";

For CommonJS:

const { throttle, debounce } = require("throttle-debounce");

Individual imports (direct from source files):

import throttle from "throttle-debounce/throttle.js";
import debounce from "throttle-debounce/debounce.js";

Basic Usage

import { throttle, debounce } from "throttle-debounce";

// Throttle: Limit function execution to once per time period
const throttleFunc = throttle(1000, (num) => {
  console.log("throttled:", num);
});

throttleFunc(1); // Executes immediately
throttleFunc(2); // Ignored
throttleFunc(3); // Ignored
// Final call will execute after 1000ms if noTrailing is false

// Debounce: Delay execution until calls stop coming
const debounceFunc = debounce(1000, (num) => {
  console.log("debounced:", num);
});

debounceFunc(1); // Won't execute
debounceFunc(2); // Won't execute
debounceFunc(3); // Will execute after 1000ms of no more calls

Architecture

Throttle Debounce is built around a shared throttling mechanism:

  • Throttle Function: Core implementation using setTimeout/clearTimeout for timing control
  • Debounce Function: Wrapper around throttle with specific debounceMode configuration
  • Cancellation System: Both functions support cancelling pending executions via .cancel() method
  • Context Preservation: Preserves the original function's this context and all arguments using .apply(), ensuring the callback executes with the same context as the wrapper function was called
  • State Management: Tracks execution timing and cancellation state internally

Capabilities

Throttling

Rate-limits function execution to occur at most once per specified time interval, useful for event handlers on scroll, resize, or other high-frequency events.

/**
 * Throttle execution of a function
 * @param {number} delay - Zero-or-greater delay in milliseconds
 * @param {Function} callback - Function to be executed after delay
 * @param {Object} [options] - Configuration options
 * @param {boolean} [options.noTrailing=false] - Skip final execution after calls stop
 * @param {boolean} [options.noLeading=false] - Skip immediate execution on first call
 * @param {boolean} [options.debounceMode] - Internal parameter for debounce mode
 * @returns {Function} Throttled wrapper function with cancel method
 */
function throttle(delay, callback, options);

Usage Examples:

import { throttle } from "throttle-debounce";

// Basic throttling - executes immediately and after delay
const basicThrottle = throttle(250, () => {
  console.log("Throttled execution");
});

// No leading execution - skip immediate execution
const noLeadingThrottle = throttle(250, handleScroll, { 
  noLeading: true 
});

// No trailing execution - skip final execution
const noTrailingThrottle = throttle(250, handleResize, { 
  noTrailing: true 
});

// Event handler example
window.addEventListener("scroll", throttle(100, () => {
  console.log("Scroll position:", window.scrollY);
}));

Debouncing

Delays function execution until after specified time has elapsed since the last invocation, ensuring function executes only once after a series of rapid calls.

/**
 * Debounce execution of a function
 * @param {number} delay - Zero-or-greater delay in milliseconds
 * @param {Function} callback - Function to be executed after delay
 * @param {Object} [options] - Configuration options
 * @param {boolean} [options.atBegin=false] - Execute at beginning vs end of calls
 * @returns {Function} Debounced wrapper function with cancel method
 */
function debounce(delay, callback, options);

Usage Examples:

import { debounce } from "throttle-debounce";

// Basic debouncing - executes after calls stop
const searchDebounce = debounce(300, (query) => {
  performSearch(query);
});

// Execute at beginning of call series
const saveDebounce = debounce(1000, saveData, { 
  atBegin: true 
});

// Input field example
document.getElementById("search").addEventListener("input", 
  debounce(300, (event) => {
    console.log("Search for:", event.target.value);
  })
);

Cancellation

Both throttled and debounced functions support cancelling pending executions.

/**
 * Cancel pending function executions and optionally prevent future executions
 * @param {Object} [options] - Cancel configuration
 * @param {boolean} [options.upcomingOnly=false] - If false (default), cancels all pending executions and prevents future ones until function is called again. If true, cancels only the next scheduled execution while allowing future executions to proceed normally.
 */
throttledFunction.cancel(options);
debouncedFunction.cancel(options);

Usage Examples:

const throttleFunc = throttle(1000, handleEvent);
const debounceFunc = debounce(1000, handleInput);

// Cancel all pending and future executions
// Clears any pending timeout and sets internal cancelled flag
throttleFunc.cancel();
debounceFunc.cancel();

// Cancel only the next scheduled execution
// Clears pending timeout but allows future calls to work normally
debounceFunc.cancel({ upcomingOnly: true });

// Component cleanup example with context preservation
class MyComponent {
  constructor() {
    // Context is automatically preserved - no need for .bind()
    this.handleScroll = throttle(100, this.onScroll);
  }
  
  onScroll() {
    // 'this' refers to MyComponent instance
    console.log('Scrolling in component:', this.constructor.name);
  }
  
  destroy() {
    this.handleScroll.cancel(); // Clean up pending executions
  }
}

Types

// Throttle options
interface ThrottleOptions {
  /** Skip final execution after calls stop */
  noTrailing?: boolean;
  /** Skip immediate execution on first call */
  noLeading?: boolean;
  /** Internal parameter for debounce mode */
  debounceMode?: boolean;
}

// Debounce options  
interface DebounceOptions {
  /** Execute at beginning vs end of calls */
  atBegin?: boolean;
}

// Cancel options
interface CancelOptions {
  /** Cancel only next execution, not all future ones */
  upcomingOnly?: boolean;
}

// Throttled/Debounced function interface
interface ThrottledFunction extends Function {
  /** Cancel pending executions */
  cancel(options?: CancelOptions): void;
}