npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@avatijs/debounce

v0.1.1

Published

Debounce package part of Avati project

Downloads

69

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.