TypeScript Debounce Decorator

0.0.18 · active · verified Sun Apr 19

typescript-debounce-decorator provides a lightweight and dependency-free TypeScript decorator for debouncing class methods. It enables developers to control the execution frequency of functions, preventing rapid, successive calls. The current stable version is 0.0.18, and while release cadence isn't explicitly stated, the version number suggests a mature, low-churn utility. Key differentiators include its minimal footprint (1KB after compression) and zero external dependencies, making it an ideal choice for projects prioritizing bundle size and avoiding dependency bloat. It supports both leading and trailing edge debouncing and offers a `cancel` function to abort pending debounced calls. A notable characteristic is that the return values of decorated methods are inherently discarded.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to apply the `@debounce` decorator to a class method, configure it for leading-edge execution, and use the `cancel` function to prevent pending debounced calls from firing.

import { debounce, cancel } from "typescript-debounce-decorator";

class MyService {
  private count: number = 0;

  constructor() {
    // Simulate user interaction
    setInterval(() => {
      console.log(`Calling increment by interval... current count: ${this.count}`);
      this.increment();
    }, 200);

    // Schedule a cancellation after some time
    setTimeout(() => {
      console.log("Attempting to cancel pending increments...");
      this.clearPending();
    }, 1500);
  }

  @debounce(1000, { leading: true }) // Debounce for 1 second, fire on leading edge
  increment() {
    this.count++;
    console.log(`Incremented! New count: ${this.count}`);
  }

  clearPending() {
    cancel(this.increment);
    console.log("Cancellation command issued.");
  }
}

new MyService();

view raw JSON →