JSPM

@avatijs/debounce

0.1.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 37
  • Score
    100M100P100Q84046F
  • License MIT

Debounce package part of Avati project

Package Exports

  • @avatijs/debounce
  • @avatijs/debounce/package.json

Readme

Advanced TypeScript Debounce Utility

A highly configurable debounce utility with TypeScript support, providing features like leading/trailing edge execution, cancellation, immediate flush, maximum wait time, and proper Promise handling.

Features

  • ๐ŸŽฏ Configurable leading/trailing edge execution
  • ๐Ÿšซ Cancelable debounced functions
  • โšก Immediate flush capability
  • โฑ๏ธ Maximum wait time option
  • ๐Ÿ”„ Promise-based return values
  • ๐ŸŽญ AbortController support
  • ๐Ÿž Debug mode
  • ๐Ÿ“ Comprehensive TypeScript types
  • ๐Ÿงน Proper cleanup utilities

Installation

npm install @avatijs/debounce

Basic Usage

import { debounce } from '@your-org/debounce-utility';

// Simple debounce
const debouncedFn = debounce(async (x: number) => x * 2, { 
  wait: 1000 
});

// Call the debounced function
await debouncedFn(5); // Will execute after 1000ms

// With debug logging
const debuggedFn = debounce(async (x: number) => x * 2, {
  wait: 1000,
  debug: true
});

// With abort controller
const controller = new AbortController();
const abortableFn = debounce(async (x: number) => x * 2, {
  wait: 1000,
  signal: controller.signal
});

// Cleanup when done
debouncedFn.cleanup();

API Reference

debounce<T>(func: T, options?: DebounceOptions): DebouncedFunction<T>

Creates a debounced version of the provided function.

Parameters

func: T

The function to debounce. Can be synchronous or asynchronous.

options: DebounceOptions

Configuration options for the debounced function.

interface DebounceOptions {
  readonly wait?: number;      // Delay in milliseconds (default: 0)
  readonly leading?: boolean;  // Execute on leading edge (default: false)
  readonly trailing?: boolean; // Execute on trailing edge (default: true)
  readonly maxWait?: number;   // Maximum time to wait
  readonly debug?: boolean;    // Enable debug logging (default: false)
  readonly signal?: AbortSignal; // AbortController signal
}

Returns

Returns a debounced function with the following interface:

interface DebouncedFunction<T> {
  (...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;
  readonly cancel: () => void;
  readonly flush: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;
  readonly pending: () => boolean;
  readonly cleanup: () => void;
}

Advanced Usage Examples

Leading Edge Execution

const leadingDebounce = debounce(
  (value: string) => console.log(value),
  { 
    wait: 1000, 
    leading: true,
    trailing: false 
  }
);

// Executes immediately, then ignores calls for 1000ms
leadingDebounce("First");
leadingDebounce("Second"); // Ignored
leadingDebounce("Third");  // Ignored

Maximum Wait Time

const maxWaitDebounce = debounce(
  (value: string) => console.log(value),
  { 
    wait: 1000, 
    maxWait: 5000 
  }
);

// Will execute after 5000ms maximum, even if called continuously
const interval = setInterval(() => maxWaitDebounce("test"), 100);

With AbortController

const controller = new AbortController();

const abortableDebounce = debounce(
  async (value: string) => {
    await someAsyncOperation(value);
  },
  { 
    wait: 1000,
    signal: controller.signal 
  }
);

// Later, abort all pending operations
controller.abort();

Debug Mode

const debugDebounce = debounce(
  (value: string) => console.log(value),
  { 
    wait: 1000,
    debug: true 
  }
);

// Will log detailed information about internal state
debugDebounce("test");

Handling Return Values

const asyncDebounce = debounce(
  async (x: number): Promise<number> => {
    await delay(100);
    return x * 2;
  },
  { wait: 1000 }
);

// Get the result
const result = await asyncDebounce(5);
console.log(result); // 10

Cleanup

const debouncedFn = debounce((x: number) => x * 2, { wait: 1000 });

// Use the function
debouncedFn(5);

// Clean up when done
debouncedFn.cleanup();

Best Practices

  1. Always Clean Up: Call cleanup() when you're done with the debounced function to prevent memory leaks:
const debouncedFn = debounce(myFunc, { wait: 1000 });

// When done:
debouncedFn.cleanup();
  1. Error Handling: Always handle potential errors in async operations:
const debouncedFn = debounce(async () => {
  try {
    await debouncedOperation();
  } catch (error) {
    // Handle error
  }
});
  1. TypeScript Usage: Leverage TypeScript's type system:
interface MyFuncParams {
  id: number;
  name: string;
}

const typedDebounce = debounce(
  (params: MyFuncParams) => console.log(params),
  { wait: 1000 }
);

// TypeScript will enforce correct parameter types
typedDebounce({ id: 1, name: "test" });

Common Gotchas

  1. Memory Leaks: Not calling cleanup() when done can lead to memory leaks.
  2. Shared State: Be careful with shared state in debounced functions.
  3. Error Handling: Always handle potential errors in async operations.
  4. Maximum Wait Time: Setting maxWait less than wait will throw an error.

Contributing

Contributions are welcome! Please read our contributing guide for details on our code of conduct and the process for submitting pull requests.

License

This project is licensed under the MIT License - see the LICENSE file for details.