Function Throttling with TypeScript

1.1.0 · active · verified Sun Apr 19

The `throttle-typescript` package provides a lightweight, TypeScript-first utility for function throttling. It enables developers to limit the rate at which a given function can be invoked, which is crucial for performance optimization in applications dealing with high-frequency events like window resizing, scrolling, or user input. The current stable version is 1.1.0, featuring an updated return value mechanism that now provides the result of the last successful function execution, alongside refined TypeScript type definitions. The library's core differentiator is its native inclusion of TypeScript types, eliminating the need for separate `@types/` packages and ensuring a smooth development experience within TypeScript projects. While the release cadence appears stable rather than rapid, it indicates a focus on robustness and type correctness. This package is ideal for scenarios where continuous event handling needs to be managed efficiently to prevent UI jank and improve overall responsiveness. It contrasts with debouncing by ensuring periodic execution rather than waiting for an idle period.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to install `throttle-typescript` and use the `throttle` function to limit the execution rate of an event handler (e.g., `window.resize`) and direct function calls, showcasing its behavior.

import { throttle } from 'throttle-typescript';

// A function that simulates some expensive operation, like a complex UI update
let executionCount = 0;
function handleExpensiveOperation() {
    executionCount++;
    const timestamp = new Date().toLocaleTimeString();
    console.log(`[${timestamp}] Heavy operation executed! Count: ${executionCount}`);
    // In a real application, this might involve DOM manipulation, recalculations, network requests, etc.
}

// Create a throttled version of the function
// It will run at most once every 200 milliseconds.
const throttledHandler = throttle(handleExpensiveOperation, 200);

// Attach the throttled function to a common high-frequency event, like window resize
window.addEventListener('resize', throttledHandler);

// You can also call it directly, and it will respect the throttle limit
let intervalCalls = 0;
const intervalId = setInterval(() => {
    if (intervalCalls >= 10) {
        clearInterval(intervalId);
        console.log('Stopped interval calls.');
        return;
    }
    console.log(`Calling throttledHandler from interval (call ${intervalCalls + 1})...`);
    throttledHandler();
    intervalCalls++;
}, 50);

console.log("Setup complete. Try resizing your browser window or observe the interval calls in the console.");

view raw JSON →