Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
Socket

@avatijs/debounce

Package Overview
Dependencies
Maintainers
0
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@avatijs/debounce

Debounce package part of Avati project

Source
npmnpm
Version
0.1.1
Version published
Maintainers
0
Created
Source

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

  • 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();
  • Error Handling: Always handle potential errors in async operations:
const debouncedFn = debounce(async () => {
  try {
    await debouncedOperation();
  } catch (error) {
    // Handle error
  }
});
  • 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

  • Memory Leaks: Not calling cleanup() when done can lead to memory leaks.
  • Shared State: Be careful with shared state in debounced functions.
  • Error Handling: Always handle potential errors in async operations.
  • 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.

Keywords

avati

FAQs

Package last updated on 20 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts