@nixat/debounce
v1.0.1
Published
A utility function to limit the rate at which a function can fire
Readme
@nixat/debounce
A utility function to limit the rate at which a function can fire.
Installation
# Using npm
npm install @nixat/debounce
# Using yarn
yarn add @nixat/debounce
# Using pnpm
pnpm add @nixat/debounceUsage
import { debounce, throttle } from '@nixat/debounce';
// Basic debounce
function saveToDatabase(data) {
// Expensive operation
console.log('Saving data:', data);
}
// Create a debounced version that only executes after 300ms of inactivity
const debouncedSave = debounce(saveToDatabase, 300);
// Call it multiple times
debouncedSave({ id: 1 });
debouncedSave({ id: 2 });
debouncedSave({ id: 3 });
// Only the last call with { id: 3 } will be executed after 300ms
// With options
const debouncedSearch = debounce(searchFunction, 300, {
leading: true, // Execute on the leading edge of the timeout
trailing: true, // Execute on the trailing edge of the timeout
maxWait: 1000 // Maximum time to wait before forced execution
});
// Cancel a pending invocation
debouncedSearch.cancel();
// Immediately invoke a pending function call
debouncedSearch.flush();
// Throttle - limit execution to at most once per 100ms
function handleScroll(event) {
console.log('Scroll position:', window.scrollY);
}
const throttledScroll = throttle(handleScroll, 100);
// Attach to scroll event
window.addEventListener('scroll', throttledScroll);API
debounce(func, wait, options)
Creates a debounced function that delays invoking the provided function until after wait milliseconds have elapsed since the last time it was invoked.
Parameters
func- The function to debouncewait- The number of milliseconds to delay (default: 0)options- The options objectleading- Iftrue, the function will be called on the leading edge of the timeouttrailing- Iftrue, the function will be called on the trailing edge of the timeout (default: true)maxWait- Maximum time the function is allowed to be delayed before it's invoked
Returns
A debounced function that can be canceled or flushed.
throttle(func, wait, options)
Creates a throttled function that only invokes the provided function at most once per every wait milliseconds.
Parameters
func- The function to throttlewait- The number of milliseconds to throttle invocations to (default: 0)options- The options objectleading- Iftrue, the function will be called on the leading edge of the timeout (default: true)trailing- Iftrue, the function will be called on the trailing edge of the timeout (default: true)
Returns
A throttled function that can be canceled or flushed.
License
MIT
