@avatijs/debounce

中文文档
0.1.3发布于 2024/11/24MITTypeScriptESM + CJS零依赖近 30 天下载 2009

Debounce package part of Avati project

原始使用文档
文档目录11 节
  1. Introduction
  2. 🌟 Why Another Debounce Library?
  3. 🎯 When You Need This
  4. 🚀 Installation
  5. 📘 Quick Start
  6. Features
  7. Demo
  8. Changelog
  9. Contributing
  10. How to Contribute
  11. License

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

版本与发布记录

@avatijs/debounce 共发布 3 个版本,首次发布于 2024/11/21;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.1.3latest2024/11/242 年前
0.1.22024/11/232 年前
0.1.12024/11/212 年前

关于 @avatijs/debounce 的常见问题

@avatijs/debounce 是什么?

Debounce package part of Avati project

如何安装 @avatijs/debounce?

在项目目录运行 npm install @avatijs/debounce,或使用 pnpm add / yarn add / bun add。

@avatijs/debounce 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@avatijs/debounce 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@avatijs/debounce 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.20.5。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@avatijs/debounce 可以商用吗?

@avatijs/debounce 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@avatijs/debounce 的下载量有多少?

根据 npm 官方下载统计,@avatijs/debounce 在 2026/10/07 – 2026/11/05 这 30 天内被下载 2,009 次,日均约 67 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@avatijs/debounce 还在维护吗?

最新版本 0.1.3 发布于 2024/11/24(2 年前);至今共发布 3 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/11/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。