📊 Sampling Function: Execute Once Every N Calls
Category: js / utils
Difficulty: medium
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. What Is a Sampling Function? 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: Rate-limiting logs in noisy systems. Sampling user interactions for telemetry. Reducing computational overhead in frequently triggered UI events. Unlike throttling (which limits function execution by time) or debouncing (which delays execution until quiet time), sampling is count-based. Code Example Here's a JavaScript implementation of a sampler function: [code example] Usage: [code example] How It Works Internally, sampler: Tracks how many times the returned function has been called (callCount). Executes the original function only when 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. Use Cases Sampling analytics events in high-frequency environments. Noise reduction in event-driven systems (e.g., mouse movement, scroll). Debug logging only every N* times to avoid console spam. Throttling vs Sampling Throttling Time-based Limit execution rate Scroll throttling...