In modern JavaScript development, controlling when and how often a function executes is critical for performance optimization and behavior control. Among techniques like throttling and debouncing, sampling offers a unique mechanism: execute a function once for every N calls.
A sampling function ensures that a given function runs only once after every fixed number of calls, say every 4th call. This is particularly useful in scenarios like:
Unlike throttling (which limits function execution by time) or debouncing (which delays execution until quiet time), sampling is count-based.
Here's a JavaScript implementation of a sampler function:
function sampler(fn, count) { let callCount = 0; return function(...args) { callCount++; if (callCount % count === 0) { fn.apply(this, args); } }; }
function message() { console.log("hello"); } const sample = sampler(message, 4); sample(); // no output sample(); // no output sample(); // no output sample(); // logs "hello" sample(); // no output sample(); // no output sample(); // no output sample(); // logs "hello"
Internally, sampler:
callCount).callCount is divisible evenly by the given count (callCount % count === 0).It uses closures to maintain internal state across invocations β an elegant and idiomatic pattern in JavaScript.
| Feature | Throttling | Sampling |
|---|---|---|
| Basis | Time-based | Call-count-based |
| When used | Limit execution rate | Trigger function every Nth time |
| Example use case | Scroll throttling | Log sampling |
Sampling is a subtle but powerful tool when you need deterministic execution control based on call frequency. It's particularly valuable in analytics-heavy or high-frequency event environments, where precision and control outweigh sheer throughput.
Test your understanding with 3 quick questions