A Basic debounce
| |
debounce with promise
If you trigger debounce while dragging the mouse, but the wrapped function calls an API and returns a Promise, you often want to run only the last invocation. How should debounce be written for that?
Lodash’s debounce checks that func is a function:
| |
For async work you need a small variant. The idea is straightforward:
Only the last Promise
| |
Every call gets a Promise, flushed together after delay
| |
API calls: throttle, cancel, retry
For API calls, throttle is also common when you want at most one request per time window.
More involved cases include cancel and retry (often with exponential backoff). When the number of promises is very large—for example, we once had 1000+ concurrent promises—you need more structure:
- Batch promises — e.g. 20 per group.
- Unique IDs — tie each promise to a task id.
- Logging — per-promise logs for debugging (we sent ours to Splunk).
- Cancel — whether in-flight work should be aborted.
- Retry — for Ajax APIs, exponential backoff for retry delays is a good fit.
The implementation is tightly coupled to the product; no sample code here.