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.3

Published

Debounce package part of Avati project

Downloads

199

Readme

TypeScript Debounce

npm version TypeScript License

Introduction

TypeScript Debounce is an elegant, robust debounce utility that brings the power of controlled function execution to your TypeScript applications. It provides a clean, type-safe API for managing function call rates, preventing resource overuse, and improving application performance.

🌟 Why Another Debounce Library?

While there are many debounce implementations available, this library stands out by offering:

  • Full TypeScript Support: Built from the ground up with TypeScript, providing complete type safety and excellent IDE integration
  • Promise-Based API: Modern async/await support with proper error handling
  • Configurable Execution: Control both leading and trailing edge execution
  • Resource Management: Built-in cleanup and cancellation support
  • Debug Support: Comprehensive logging for development troubleshooting
  • Maximum Wait Time: Guarantee execution for long-running debounce periods
  • Zero Dependencies: Lightweight and self-contained

🎯 When You Need This

Debouncing is crucial in many common development scenarios:

  1. Search Input Handling

    // Without debounce - Makes API call on every keystroke
    searchInput.addEventListener('input', async (e) => {
        const results = await searchAPI(e.target.value); // 🔴 Excessive API calls
    });
    
    // With debounce - Waits for user to stop typing
    const debouncedSearch = debounce(async (value: string) => {
        const results = await searchAPI(value);
    }, { wait: 300 }); // ✅ Single API call after typing stops
  2. Window Resize Handling

    // Without debounce - Recalculates layout on every resize event
    window.addEventListener('resize', () => {
        recalculateLayout(); // 🔴 Performance bottleneck
    });
    
    // With debounce - Controlled recalculation
    const debouncedResize = debounce(() => {
        recalculateLayout();
    }, { wait: 150 }); // ✅ Smooth performance
  3. Form Validation

    // Without debounce - Validates on every change
    input.addEventListener('input', async (e) => {
        await validateField(e.target.value); // 🔴 Excessive validation
    });
    
    // With debounce - Validates after user stops typing
    const debouncedValidate = debounce(async (value: string) => {
        await validateField(value);
    }, { wait: 400 }); // ✅ Efficient validation
  4. Real-time Saving

    // Without debounce - Saves on every change
    editor.on('change', async (content) => {
        await saveContent(content); // 🔴 Too many save operations
    });
    
    // With debounce - Intelligently batches saves
    const debouncedSave = debounce(async (content: string) => {
        await saveContent(content);
    }, { wait: 1000 }); // ✅ Optimized saving

🚀 Installation

npm install typescript-debounce
# or
yarn add typescript-debounce
# or
pnpm add typescript-debounce

📘 Quick Start

import { debounce } from '@avatijs/debounce';

// Create a debounced function
const debouncedFn = debounce(async (value: string) => {
    const result = await api.search(value);
    updateUI(result);
}, {
    wait: 300,                // Wait 300ms after last call
    leading: false,           // Don't execute on leading edge
    trailing: true,           // Execute on trailing edge
    maxWait: 1000,           // Maximum time to wait
    debug: true,             // Enable debug logging
    onError: console.error    // Error handling
});

// Use the debounced function
try {
    await debouncedFn('search term');
} catch (error) {
    handleError(error);
}

Features

  • Type Safety: Full TypeScript support with intelligent type inference
  • Promise Support: Built-in handling of async functions
  • Cancellation: Support for AbortController and manual cancellation
  • Maximum Wait: Configure maximum delay before forced execution
  • Edge Control: Configure execution on leading and/or trailing edge
  • Debug Mode: Comprehensive logging for development
  • Error Handling: Robust error handling with custom callbacks
  • Resource Management: Automatic cleanup of resources
  • Memory Efficient: Proper cleanup and memory management

Demo

Checkout the Demo to see TypeScript Debounce in action.

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

I welcome contributions from developers of all experience levels. If you have an idea, found a bug, or want to improve something, I encourage you to get involved!

How to Contribute

  1. Read Contributing Guide for details on how to get started.
  2. Fork the repository and make your changes.
  3. Submit a pull request, and we’ll review it as soon as possible.

License

MIT License

Avati is open-source and distributed under the MIT License.


Follow on Twitter Follow on LinkedIn Follow on Medium Made with ❤️ Star on GitHub Follow on GitHub