smart-debounce
v1.0.4
Published
A smart, tiny, zero-dependency debounce function for sync and async functions in TypeScript.
Maintainers
Readme
Smart Debounce
Smart Debounce is a lightweight, type-safe, zero-dependency utility for debouncing function calls in JavaScript/TypeScript. It offers advanced features such as async support, cancellation, rate-limiting, and more.
Features
- Type-safe: Written in TypeScript with full type safety.
- Zero dependencies: No third-party dependencies.
- Async support: Debounced functions work seamlessly with promises.
- Rate-limiting: Support for controlling function execution frequency.
- Cancellation and Flush: Manual control to cancel or flush the debounce queue.
- Leading and Trailing edge support: Control whether the debounced function runs at the beginning or end of the debounce interval.
- Max Calls per Wait Window: Option to limit the number of calls within a single debounce window.
Installation
You can install the package via npm:
npm install smart-debounceOr using yarn:
yarn add smart-debounceUsage
Basic Example
import { smartDebounce } from 'smart-debounce';
const logMessage = (message: string) => {
console.log(`Logged: ${message}`);
};
const debouncedLog = smartDebounce(logMessage, { wait: 1000 });
debouncedLog('Message 1'); // This will be debounced
debouncedLog('Message 2'); // This will override the previous call
debouncedLog('Message 3'); // This will trigger the log after 1 secondAdvanced Example
import { smartDebounce } from 'smart-debounce';
const fetchUser = async (query: string) => {
console.log(`Fetching user for: ${query}`);
// Simulate an API request
return new Promise(resolve => setTimeout(() => resolve({ query, user: 'John Doe' }), 2000));
};
const debouncedFetchUser = smartDebounce(fetchUser, {
wait: 1000,
maxWait: 3000,
leading: false,
trailing: true,
});
debouncedFetchUser('user 1');
debouncedFetchUser('user 2');
debouncedFetchUser('user 3');
// This will log the last request after 1 secondManual Control
You can cancel or flush the debounce queue manually:
debouncedLog.cancel(); // Cancels the debounce
debouncedLog.flush(); // Executes the debounced function immediatelyReact Example
import React, { useState } from 'react';
import { smartDebounce } from 'smart-debounce';
const SearchComponent = () => {
const [query, setQuery] = useState('');
const handleChange = smartDebounce((event: React.ChangeEvent<HTMLInputElement>) => {
console.log('Searching for:', event.target.value);
// Perform search or API call here
}, { wait: 500 });
return (
<div>
<input
type="text"
value={query}
onChange={(e) => {
setQuery(e.target.value);
handleChange(e);
}}
placeholder="Search..."
/>
</div>
);
};
export default SearchComponent;Angular Example
import { Component } from '@angular/core';
import { smartDebounce } from 'smart-debounce';
@Component({
selector: 'app-search',
template: `
<input [(ngModel)]="query" (ngModelChange)="onSearch($event)" placeholder="Search..."/>
`,
})
export class SearchComponent {
query: string = '';
onSearch = smartDebounce((query: string) => {
console.log('Searching for:', query);
// Perform search or API call here
}, { wait: 500 });
}API
smartDebounce(fn, options)
- fn: The function to debounce (required).
- options: Configuration options (optional).
wait: Delay in milliseconds before calling the function (default: 300).maxWait: Maximum time before the function is called (default: undefined).leading: Iftrue, the function is invoked at the leading edge of the wait interval (default: false).trailing: Iftrue, the function is invoked at the trailing edge of the wait interval (default: true).maxCallsPerWaitWindow: Maximum number of calls allowed within a debounce window (default: undefined).
cancel()
- Cancels the current debounce and clears any pending executions.
flush()
- Immediately invokes the debounced function and clears any pending executions.
reset()
- Resets the debounce state, clearing any timeouts and pending calls.
License
MIT License
