{"id":12167,"library":"ts-debounce","title":"TypeScript Debounce Function","description":"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.","status":"active","version":"5.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/chodorowicz/ts-debounce","tags":["javascript","TypeScript","ts","TS","std lib","function","debounce","wait","typescript"],"install":[{"cmd":"npm install ts-debounce","lang":"bash","label":"npm"},{"cmd":"yarn add ts-debounce","lang":"bash","label":"yarn"},{"cmd":"pnpm add ts-debounce","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary `debounce` utility is a named export. This is the standard way to import in modern JavaScript/TypeScript.","symbol":"debounce","correct":"import { debounce } from 'ts-debounce';"},{"note":"The library does not provide a default export. Attempting a default import will result in an undefined value.","wrong":"import debounce from 'ts-debounce';","symbol":"debounce"},{"note":"For CommonJS environments, `debounce` must be destructured from the `require` call as it is a named export. Directly assigning `require('ts-debounce')` will not yield the function itself.","wrong":"const debounce = require('ts-debounce');","symbol":"debounce","correct":"const { debounce } = require('ts-debounce');"},{"note":"For type-only imports, explicitly use `import type` to ensure correct tree-shaking and to avoid accidental runtime imports.","symbol":"DebouncedFunction","correct":"import type { DebouncedFunction } from 'ts-debounce';"}],"quickstart":{"code":"import { debounce } from 'ts-debounce';\n\n// Example 1: Basic debouncing for input handling\nfunction logInput(value: string) {\n  console.log('Debounced input:', value);\n}\n\nconst debouncedLog = debounce(logInput, 500);\n\n// Simulate rapid input events\ndebouncedLog('a');\ndebouncedLog('ap');\ndebouncedLog('app');\n// This call will execute 500ms after the last 'app' call\nsetTimeout(() => debouncedLog('apple'), 600);\n\n// Example 2: Debouncing an asynchronous function with cancellation\nconst fetchUserData = async (userId: string): Promise<string> => {\n  console.log(`Fetching data for ${userId}...`);\n  return new Promise(resolve => setTimeout(() => resolve(`Data for ${userId}`), 1000));\n};\n\nconst debouncedFetch = debounce(fetchUserData, 300);\n\nasync function testAsyncDebounce() {\n  console.log(\"Calling async debounced function rapidly...\");\n  const p1 = debouncedFetch('user1');\n  const p2 = debouncedFetch('user2');\n  const p3 = debouncedFetch('user3'); // This will be the one that gets executed if not cancelled\n\n  setTimeout(() => {\n    debouncedFetch.cancel(); // Cancel the pending 'user3' call\n    console.log(\"Debounced fetch cancelled.\");\n  }, 400); // This will happen before 'user3' would execute\n\n  try {\n    // p1 and p2 will reject if the final call is cancelled\n    await Promise.allSettled([p1, p2, p3]);\n    console.log(\"Promises settled (some may be rejected due to cancellation).\");\n  } catch (e: any) {\n    console.warn(\"An unexpected error occurred during async debounce test:\", e.message);\n  }\n}\n\ntestAsyncDebounce();","lang":"typescript","description":"Demonstrates basic function debouncing for a synchronous logger and advanced usage involving asynchronous functions with Promise support and the cancellation mechanism."},"warnings":[{"fix":"Review and update type annotations for functions debounced in version 5.0.0, especially those returning promises, to align with the stricter `Awaited` inference. Adjust expectations for `Promise` return types to `Promise<T>` instead of `Promise<Promise<T>>`.","message":"Version 5.0.0 introduces the use of the `Awaited` type to prevent `Promise<Promise<T>>` in promise-returning debounced functions. While an improvement, this change might subtly alter the inferred return types, potentially causing existing type checks to break if they were expecting less specific types.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Update your function signatures and event handlers to correctly type the arguments based on the improved inference (e.g., `(event: Event)` instead of `(event: any)`). This generally leads to more robust and safer code.","message":"Version 4.0.0 significantly improved type inference for arguments passed to the debounced function. This means types that were previously inferred as `any` (e.g., event objects in event listeners) are now much more specific. If your existing code relied on the looser `any` type, it might now trigger TypeScript compilation errors.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Ensure that your target execution environment provides a global `Promise` implementation, or include a polyfill (e.g., `core-js`) if targeting older environments.","message":"Starting from version 3.0.0, `ts-debounce` introduced Promise support. This functionality relies on the global `Promise` object being available in the execution environment. In older browser environments or Node.js versions, a global `Promise` polyfill might be required.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Carefully consider the interaction of `isImmediate` with `waitMilliseconds`. If you always want a delay before the first execution, do not set `isImmediate` to `true`. Read the documentation thoroughly to understand its behavior.","message":"The `isImmediate` option, when set to `true`, causes the `originalFunction` to be invoked immediately on the first call, and subsequent calls are debounced. If not fully understood, this can lead to unexpected immediate executions when the intention was a delayed one.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Update the type signature of your debounced function's arguments to match the expected specific type (e.g., `(event: Event)`). For example, `debounce((event: Event) => { /* ... */ }, 300);`","cause":"Improved type inference in `ts-debounce` v4.0.0 and above now provides more specific types for function arguments, removing reliance on `any`.","error":"Argument of type 'any' is not assignable to parameter of type 'Event'."},{"fix":"Ensure you are destructuring the named export: `const { debounce } = require('ts-debounce');`. If using ES Modules, prefer `import { debounce } from 'ts-debounce';`.","cause":"This typically occurs in CommonJS environments when attempting to `require('ts-debounce')` and expecting a default export, or attempting to use `const debounce = require('ts-debounce')` instead of destructuring.","error":"TypeError: Cannot read property 'debounce' of undefined"},{"fix":"Include a `Promise` polyfill (e.g., from `core-js` or `es6-promise`) in your application bundle to provide the necessary global `Promise` implementation.","cause":"Running `ts-debounce` v3.0.0 or higher in a JavaScript environment that lacks a global `Promise` object (e.g., older browsers or Node.js without a polyfill).","error":"ReferenceError: Promise is not defined"}],"ecosystem":"npm"}