How p-throttle works
mainp-throttle rate-limits function calls without discarding them. Unlike debouncing or throttling that might drop calls, p-throttle queues all calls and executes them sequentially or according to the specified limit. This ensures that every call is eventually executed with its original context and arguments preserved, making it ideal for external API interactions where call loss is unacceptable.
It works with both async/promise-returning functions and normal functions.
import pThrottle from 'p-throttle';
const throttle = pThrottle({
limit: 2,
interval: 1000
});
const throttled = throttle(async index => {
return `${index}: processed`;
});
// All calls are queued and executed at the specified rate
for (let index = 1; index <= 6; index++) {
(async () => {
console.log(await throttled(index));
})();
}