### Install p-throttle package Source: https://github.com/sindresorhus/p-throttle/blob/main/readme.md This command installs the p-throttle library from the npm registry, making it available for use in your project. ```sh npm install p-throttle ``` -------------------------------- ### Handling Throttled Delays with onDelay Source: https://github.com/sindresorhus/p-throttle/blob/main/readme.md Shows how to use the `onDelay` callback option to get notified when a function call is delayed because the throttling limit has been reached within the current interval. The arguments passed to the delayed function call are provided to the `onDelay` callback. ```js import pThrottle from 'p-throttle'; const throttle = pThrottle({ limit: 2, interval: 1000, onDelay: (a, b) => { console.log(`Reached interval limit, call is delayed for ${a} ${b}`); }, }); const throttled = throttle((a, b) => { console.log(`Executing with ${a} ${b}...`); }); await throttled(1, 2); await throttled(3, 4); await throttled(5, 6); //=> Executing with 1 2... //=> Executing with 3 4... //=> Reached interval limit, call is delayed for 5 6 //=> Executing with 5 6... ``` -------------------------------- ### Basic Usage with p-throttle Source: https://github.com/sindresorhus/p-throttle/blob/main/readme.md Demonstrates how to initialize p-throttle with a limit of 2 calls per 1000ms interval and apply it to an async function. It shows how calls are queued and executed according to the throttle settings, illustrating the time difference between executions. ```js import pThrottle from 'p-throttle'; const now = Date.now(); const throttle = pThrottle({ limit: 2, interval: 1000 }); const throttled = throttle(async index => { const secDiff = ((Date.now() - now) / 1000).toFixed(); return `${index}: ${secDiff}s`; }); for (let index = 1; index <= 6; index++) { (async () => { console.log(await throttled(index)); })(); } //=> 1: 0s //=> 2: 0s //=> 3: 1s //=> 4: 1s //=> 5: 2s //=> 6: 2s ``` -------------------------------- ### Aborting Throttled Calls with AbortSignal Source: https://github.com/sindresorhus/p-throttle/blob/main/readme.md Illustrates how to use an AbortSignal to cancel pending throttled function calls. When the signal is aborted, any calls that are currently queued and waiting to execute will have their promises rejected with the specified reason. ```js import pThrottle from 'p-throttle'; const controller = new AbortController(); const throttle = pThrottle({ limit: 2, interval: 1000, signal: controller.signal }); const throttled = throttle(() => { console.log('Executing...'); }); await throttled(); await throttled(); controller.abort('aborted') await throttled(); //=> Executing... //=> Executing... //=> Promise rejected with reason `aborted` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.