DevFiddleDevFiddle
HomeToolsSnippetsArticles
Explore tools
Home>Snippets>Debounce Function with TypeScript
TypeScript
#Utilities#Performance#Functions

Debounce Function with TypeScript

A type-safe debounce implementation that delays executing a function until a specified wait time has elapsed.

October 10, 20262 min read

Debouncing is a programming pattern that limits the rate at which a function gets invoked. It is particularly valuable for handling high-frequency events like keystroke searches, window resizing, or scroll tracking.

The Code

export function debounce<T extends (...args: any[]) => any>(
  fn: T,
  wait: number = 300
): ((...args: Parameters<T>) => void) & { cancel: () => void } {
  let timeoutId: ReturnType<typeof setTimeout> | null = null;
 
  const debounced = (...args: Parameters<T>) => {
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
    }
 
    timeoutId = setTimeout(() => {
      fn(...args);
      timeoutId = null;
    }, wait);
  };
 
  debounced.cancel = () => {
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
  };
 
  return debounced;
}

How It Works

  1. Timer Reset: Every time the returned debounced function is executed, any currently scheduled timer is canceled via clearTimeout.
  2. Delayed Execution: A new timer is set to execute the target function only after the specified wait milliseconds pass without another call.
  3. Cancellation Method: Attaching .cancel() allows callers (such as React useEffect cleanups) to discard pending timers before a component unmounts.
  4. Strong Typing: Generics ensure the debounced function retains the exact argument types of the original function.

Example Usage

const handleSearch = (query: string) => {
  console.log(`Searching for: ${query}`);
};
 
const debouncedSearch = debounce(handleSearch, 400);
 
// Typing "react":
debouncedSearch("r");
debouncedSearch("re");
debouncedSearch("rea");
debouncedSearch("react");
// Only executes once with "react" after 400ms of inactivity!

Related snippets

Explore more utility functions, patterns, and code snippets.

View all snippets
JavaScript
Fetch with AbortSignal Timeout

Cancel hanging HTTP requests gracefully using AbortSignal.timeout and custom fallback controllers.

#JavaScript#Fetch#Async
View snippet
JavaScript
Deep Clone Objects in Modern JavaScript

Deeply copy nested JavaScript objects and arrays using native structuredClone and fallback recursion.

#JavaScript#Objects#Data Structures
View snippet
React
useLocalStorage Custom React Hook

A robust React hook for syncing component state with window.localStorage across tabs.

#React#Hooks#LocalStorage
View snippet
About© DevFiddle 2026