Throttle Fixed Window Rate Limiter
Build a fixed-window throttle limiting calls per interval with trailing invocation for bounded request rates.
Code
export function throttle(fn,interval,{trailing=true}={}){let last=0,t=null,args=null;function f(...a){const now=Date.now(),rem=interval-(now-last);if(rem<=0){if(t){clearTimeout(t);t=null;}last=now;fn.apply(this,a);}else if(trailing){args=a;if(!t)t=setTimeout(()=>{last=Date.now();t=null;fn.apply(this,args);args=null;},rem);}}f.cancel=()=>{if(t)clearTimeout(t);t=null;args=null;};return f;}How it works
The working surface is the functions throttle and f — everything else is wiring.
Using it
The main signature reads export function throttle(fn,interval,{trailing=true}={})
Import throttle from the file and call it — the rest of the code is implementation detail.
Interactive Tools for This Topic
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `throttle`, `f` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.