back to series Implement a sampling function Mar 27, 2024
Sampling is a higher order utility function which invokes a function every n sample period. For other invocation which are not within the sampling period, it can return undefined.
Variation: Basic implementation function sampling ( fn , n ) {
function samplingFnImpl ( ... args ) {
if (invocations % n !== 0 ) {
return fn. call ( this , ... args);
// Usage of the sampling utility function
const sampledFn = sampling (() => {
console. log ( 'I will be called on every 3rd sampling period' );
sampledFn (); // yields logs here on 3th sample period
sampledFn (); // yields logs here on 6th sample period
Variation: With Last Result In this variation, if the function is invoked in non-sampling period, we simply need to return the last result saved during the sampling period invocation of function.
function sampling ( fn , n ) {
let lastResult = undefined ;
function samplingFnImpl ( ... args ) {
if (invocations % n !== 0 ) {
// simply return last saved result instead of undefined
// save result of function invocation
lastResult = fn. call ( this , ... args);
// Usage of the sampling utility function
const sampledFn = sampling (() => {
console. log ( 'I will be called on every 3rd sampling period' );
sampledFn (); // yields logs here on 2nd sample period
sampledFn (); // yields logs here on 4th sample period
sampledFn (); // yields logs here on 6th sample period
I strongly encourage you to explore and tackle additional questions in my Closure Questions for Frontend Interviews blog series.
By doing so, you can enhance your understanding and proficiency with closures, preparing you to excel in your upcoming frontend interviews.
Wishing you best. Happy Interviewing 🫡.