JavaScript Snippet

Throttle Function in JavaScript

Difficulty: Easy

Throttling caps how often a function can fire to at most once per interval, which is the right tool for scroll, mousemove, and analytics beacons. This snippet contrasts throttle against debounce, then walks from a leading-edge timestamp gate to a `setTimeout`-driven version that includes a manual `cancel`. Pick the variant that matches whether the very first call should fire immediately.

Code Snippets
/

Throttle Function in JavaScript

Throttle Function in JavaScript

Throttling caps how often a function can fire to at most once per interval, which is the right tool for scroll, mousemove, and analytics beacons. This snippet contrasts throttle against debounce, then walks from a leading-edge timestamp gate to a `setTimeout`-driven version that includes a manual `cancel`. Pick the variant that matches whether the very first call should fire immediately.

JavaScript
Easy
3 snippets
utility
code-template
performance-optimization
rate-limiting

800 views

17

The simplest throttle compares the current timestamp against the last accepted call. If at least wait milliseconds have passed, the new call goes through and the timestamp resets; otherwise it is silently dropped. This pattern fires on the leading edge (the very first call always wins) which feels responsive for analytics beacons and event logging. The downside is that if a burst of calls all land inside one window, only the first sees the latest arguments, so the trailing data is lost. Pair this with a debounce on the trailing edge if both are needed (see the Hard accordion js-throttle-leading-trailing).