TypeScript Debounce Function

5.0.0 · active · verified Sun Apr 19

This package provides a robust TypeScript implementation of the debounce function, designed to limit the rate at which a function can be called. It is currently at version 5.0.0 and sees releases driven by feature enhancements and necessary fixes, rather than a strict schedule. Key features include full TypeScript support with improved type inference, cancellation functionality, an optional `maxWait` parameter to force execution after a maximum delay, and comprehensive Promise integration, allowing debouncing of promise-returning functions and returning promises from debounced calls. It differentiates itself by being TypeScript-first, directly addressing common debounce use cases with strong typing, and offering flexibility similar to popular utility libraries like Lodash but with a smaller footprint and modern ESM support.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic function debouncing for a synchronous logger and advanced usage involving asynchronous functions with Promise support and the cancellation mechanism.

import { debounce } from 'ts-debounce';

// Example 1: Basic debouncing for input handling
function logInput(value: string) {
  console.log('Debounced input:', value);
}

const debouncedLog = debounce(logInput, 500);

// Simulate rapid input events
debouncedLog('a');
debouncedLog('ap');
debouncedLog('app');
// This call will execute 500ms after the last 'app' call
setTimeout(() => debouncedLog('apple'), 600);

// Example 2: Debouncing an asynchronous function with cancellation
const fetchUserData = async (userId: string): Promise<string> => {
  console.log(`Fetching data for ${userId}...`);
  return new Promise(resolve => setTimeout(() => resolve(`Data for ${userId}`), 1000));
};

const debouncedFetch = debounce(fetchUserData, 300);

async function testAsyncDebounce() {
  console.log("Calling async debounced function rapidly...");
  const p1 = debouncedFetch('user1');
  const p2 = debouncedFetch('user2');
  const p3 = debouncedFetch('user3'); // This will be the one that gets executed if not cancelled

  setTimeout(() => {
    debouncedFetch.cancel(); // Cancel the pending 'user3' call
    console.log("Debounced fetch cancelled.");
  }, 400); // This will happen before 'user3' would execute

  try {
    // p1 and p2 will reject if the final call is cancelled
    await Promise.allSettled([p1, p2, p3]);
    console.log("Promises settled (some may be rejected due to cancellation).");
  } catch (e: any) {
    console.warn("An unexpected error occurred during async debounce test:", e.message);
  }
}

testAsyncDebounce();

view raw JSON →