Debouncing is a technique to limit how often a function executes by delaying its execution until after a specified time has passed since the last call. This is particularly useful for:
Search input fields
Window resize handlers
Scroll event handlers
API calls triggered by user input
Auto-save functionality
This package extends basic debouncing with lifecycle hooks, immediate execution options, and flood detection.
import { debounce } from '@kreisler/debounce';const handleSearch = (query) => { console.log('Searching for:', query); // API call here};const debouncedSearch = debounce(handleSearch, 500);// User types quicklydebouncedSearch('a');debouncedSearch('ab');debouncedSearch('abc');// Only 'abc' will be searched after 500ms
import { debounce } from '@kreisler/debounce';const handleSearch = (query: string): void => { console.log('Searching for:', query); // API call here};const debouncedSearch = debounce(handleSearch, 500);// User types quicklydebouncedSearch('a');debouncedSearch('ab');debouncedSearch('abc');// Only 'abc' will be searched after 500ms
Detect when the function is being called too frequently:
import { debounce } from '@kreisler/debounce';let attemptCount = 0;const submitForm = (data) => { console.log('Submitting form:', data);};const debouncedSubmit = debounce(submitForm, 1000, { flood: 5, onFlood: (data) => { console.warn('Slow down! Too many attempts.'); // Show user notification }});// Rapid callsfor (let i = 0; i < 10; i++) { debouncedSubmit({ attempt: i });}// onFlood will be called at attempts 5 and 10
import type { TArrowFunction, TFns } from '@kreisler/debounce';// TArrowFunction: (...args: any[]) => any// TFns: Interface with all configuration options