CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-debounce

Delay function calls until a set time elapses after the last invocation

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

index.mddocs/

Debounce

Debounce provides a utility function for delaying function calls until a set time elapses after the last invocation. It prevents excessive function executions during rapid events like user input, window resizing, or API requests.

Package Information

  • Package Name: debounce
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install debounce

Core Imports

import debounce from "debounce";

For CommonJS:

const debounce = require("debounce");

Named import (also available):

import { debounce } from "debounce";
// or
const { debounce } = require("debounce");

Basic Usage

import debounce from "debounce";

function resize() {
  console.log('height', window.innerHeight);
  console.log('width', window.innerWidth);
}

// Debounce the resize function with 200ms delay
window.onresize = debounce(resize, 200);

// Check if execution is pending
console.log(window.onresize.isPending); // boolean

// Cancel any scheduled executions
window.onresize.clear();

// Execute immediately if scheduled and clear timer
window.onresize.flush();

// Execute immediately and clear timer
window.onresize.trigger();

Capabilities

Debounce Function

Creates a debounced function that delays execution until wait milliseconds have passed since its last invocation.

/**
 * Creates a debounced function that delays execution until wait milliseconds have passed
 * @param function_ - The function to debounce
 * @param wait - Milliseconds to delay (default: 100)
 * @param options - Configuration options
 * @returns Debounced function with control methods
 */
function debounce<F extends AnyFunction>(
  function_: F,
  wait?: number,
  options?: { immediate: boolean }
): DebouncedFunction<F>;

type AnyFunction = (...arguments_: readonly any[]) => unknown;

type DebouncedFunction<F extends AnyFunction> = {
  (...arguments_: Parameters<F>): ReturnType<F> | undefined;
  readonly isPending: boolean;
  clear(): void;
  flush(): void;
  trigger(): void;
};

Parameters

  • function_ (Function): The function to debounce - Required
  • wait (number): Milliseconds to delay execution - Default: 100
  • options (Object): Configuration options - Default: {}
    • immediate (boolean): Execute immediately on first call if true

Note: A boolean value for options is also supported (deprecated) where true is equivalent to { immediate: true }.

Return Value

Returns a debounced function that:

  • Accepts the same arguments as the original function
  • Returns the result of the original function or undefined if not yet executed
  • Includes control methods and properties

Control Methods and Properties

isPending (readonly boolean): Indicates whether the debounce delay is currently active.

clear(): Cancels any scheduled executions without executing the function.

flush(): If an execution is scheduled, immediately executes the function and clears the timer. Does nothing if no execution is scheduled.

trigger(): Executes the function immediately and clears the timer if it was previously set.

Usage Examples

Basic debouncing:

import debounce from "debounce";

const search = debounce((query) => {
  console.log('Searching for:', query);
}, 300);

// Only the last call will execute after 300ms of inactivity
search('a');
search('ap');
search('app');
search('apple'); // Only this will execute

Immediate execution mode:

import debounce from "debounce";

const saveData = debounce((data) => {
  console.log('Saving:', data);
}, 1000, { immediate: true });

// Executes immediately on first call, then debounces subsequent calls
saveData('data1'); // Executes immediately
saveData('data2'); // Ignored (within debounce period)
saveData('data3'); // Ignored (within debounce period)
// After 1000ms of inactivity, ready for immediate execution again

Using control methods:

import debounce from "debounce";

const processInput = debounce((input) => {
  console.log('Processing:', input);
}, 500);

processInput('test');

// Check if execution is pending
if (processInput.isPending) {
  console.log('Execution is scheduled');
}

// Cancel the scheduled execution
processInput.clear();

// Or force immediate execution
processInput('urgent');
processInput.trigger(); // Execute immediately

Context preservation:

import debounce from "debounce";

class DataProcessor {
  constructor(name) {
    this.name = name;
    this.process = debounce(this.process.bind(this), 200);
  }

  process(data) {
    console.log(`${this.name} processing:`, data);
  }
}

const processor = new DataProcessor('Main');
processor.process('data'); // Context (this.name) is preserved

Error Handling

The debounce function throws errors in the following cases:

  • TypeError: If the first parameter is not a function
  • RangeError: If the wait parameter is negative
  • Error: If a debounced method is called with different contexts of the same prototype (prevents context mixing issues)
import debounce from "debounce";

// TypeError: Expected the first parameter to be a function
const invalid1 = debounce("not a function", 100);

// RangeError: `wait` must not be negative
const invalid2 = debounce(() => {}, -100);

Install with Tessl CLI

npx tessl i tessl/npm-debounce

docs

index.md

tile.json