throttle
Creates a throttled version of a function that only invokes the original at most once per specified interval.
Import
Section titled “Import”import { throttle } from "1o1-utils";import { throttle } from "1o1-utils/throttle";Signature
Section titled “Signature”function throttle<T>({ fn, ms }: ThrottleParams<T>): Throttled<T>Parameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
| fn | T | Yes | The function to throttle |
| ms | number | Yes | Minimum interval between calls in milliseconds (non-negative) |
Returns
Section titled “Returns”Throttled<T> — The throttled function with a .cancel() method.
Examples
Section titled “Examples”const throttledScroll = throttle({ fn: () => updatePosition(), ms: 100,});
window.addEventListener("scroll", throttledScroll);
// Cancel pending trailing callthrottledScroll.cancel();Edge Cases
Section titled “Edge Cases”- Throws if
fnis not a function. - Throws if
msis not a number or isNaN. - Throws if
msis negative. - First call executes immediately.
- Subsequent calls within
msare queued; the last one fires after the interval. .cancel()clears pending calls and resets state.
Also known as
Section titled “Also known as”rate limit, limit calls, scroll handler, resize handler
Prompt suggestion
Section titled “Prompt suggestion”I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use throttle to limit a scroll event handler