Search code examples
javascripttask-queuethrottlingrate-limitingdebouncing

Throttle JavaScript function calls, but with queuing (don't discard calls)


How can a function rate-limit its calls? The calls should not be discarded if too frequent, but rather be queued up and spaced out in time, X milliseconds apart. I've looked at throttle and debounce, but they discard calls instead of queuing them up to be run in the future.

Any better solution than a queue with a process() method set on an X millisecond interval? Are there such standard implementations in JS frameworks? I've looked at underscore.js so far - nothing.


Solution

  • While the snippets offered by others do work (I've built a library based on them), for those who want to use well-supported modules, here are the top choices:

    • the most popular rate limiter is limiter
    • function-rate-limit has a simple API that works, and good usage stats on npmjs
    • valvelet, a newer module, claims to do an even better job by supporting promises, but hasn't gained popularity yet