{"id":12142,"library":"throttle-typescript","title":"Function Throttling with TypeScript","description":"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.","status":"active","version":"1.1.0","language":"javascript","source_language":"en","source_url":"git://github.com/bameyrick/throttle-typescript","tags":["javascript","throttle","throttled","function","typescript","types"],"install":[{"cmd":"npm install throttle-typescript","lang":"bash","label":"npm"},{"cmd":"yarn add throttle-typescript","lang":"bash","label":"yarn"},{"cmd":"pnpm add throttle-typescript","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The package is primarily designed for ES Modules and ships with TypeScript types. While CommonJS `require` might work in some environments, ES module import is the recommended approach for modern JavaScript and TypeScript.","wrong":"const throttle = require('throttle-typescript');","symbol":"throttle","correct":"import { throttle } from 'throttle-typescript';"}],"quickstart":{"code":"import { throttle } from 'throttle-typescript';\n\n// A function that simulates some expensive operation, like a complex UI update\nlet executionCount = 0;\nfunction handleExpensiveOperation() {\n    executionCount++;\n    const timestamp = new Date().toLocaleTimeString();\n    console.log(`[${timestamp}] Heavy operation executed! Count: ${executionCount}`);\n    // In a real application, this might involve DOM manipulation, recalculations, network requests, etc.\n}\n\n// Create a throttled version of the function\n// It will run at most once every 200 milliseconds.\nconst throttledHandler = throttle(handleExpensiveOperation, 200);\n\n// Attach the throttled function to a common high-frequency event, like window resize\nwindow.addEventListener('resize', throttledHandler);\n\n// You can also call it directly, and it will respect the throttle limit\nlet intervalCalls = 0;\nconst intervalId = setInterval(() => {\n    if (intervalCalls >= 10) {\n        clearInterval(intervalId);\n        console.log('Stopped interval calls.');\n        return;\n    }\n    console.log(`Calling throttledHandler from interval (call ${intervalCalls + 1})...`);\n    throttledHandler();\n    intervalCalls++;\n}, 50);\n\nconsole.log(\"Setup complete. Try resizing your browser window or observe the interval calls in the console.\");","lang":"typescript","description":"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."},"warnings":[{"fix":"If your code relies on the return value of the throttled function, ensure it correctly handles this new behavior. Verify that any assignments or conditional logic based on the throttled function's output are still valid.","message":"The return value of the throttled function changed in v1.1.0. It now reflects the result of the last actual execution of the underlying function. Previously, the return value behavior was less explicitly defined.","severity":"gotcha","affected_versions":">=1.1.0"},{"fix":"Preserve the `this` context by binding the method or using an arrow function: `throttle(this.myMethod.bind(this), 100)` or `throttle(() => this.myMethod(), 100)`.","message":"When throttling an object method (e.g., `this.myMethod`), the `this` context can be lost within the throttled function, leading to `TypeError: Cannot read properties of undefined`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Confirm that throttling is the correct pattern for your use case. If you need to respond to an event only once activity has ceased (e.g., searching after a user stops typing), you should use a 'debounce' utility instead.","message":"This package implements 'throttling', which ensures a function executes at most once per a specified time interval. It is not 'debouncing', which executes a function only after a period of inactivity.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Bind the method to its `this` context: `window.addEventListener('scroll', throttle(this.myMethod.bind(this), 100));` or use an arrow function: `window.addEventListener('scroll', throttle(() => this.myMethod(), 100));`","cause":"The `this` context was lost when throttling an object method without binding it.","error":"TypeError: Cannot read properties of undefined (reading 'myMethod')"},{"fix":"Use a named import: `import { throttle } from 'throttle-typescript';`","cause":"Attempting to import the `throttle` function as a default import when it is a named export.","error":"Module '\"throttle-typescript\"' has no exported member 'default'."},{"fix":"Ensure the package is installed: `npm install throttle-typescript` or `yarn add throttle-typescript`. Double-check the import statement for typos: `import { throttle } from 'throttle-typescript';`","cause":"The package has not been installed, or there is a typo in the import path. For TypeScript, it can also indicate an issue with `tsconfig.json` or module resolution.","error":"Cannot find module 'throttle-typescript' or its corresponding type declarations."}],"ecosystem":"npm"}