Create a function in JavaScript that accepts a function as input and a count and executes that input function once for a given count of calls. Known as sampling function.
Example
function message(){
console.log("hello");
}
const sample = sampler(message, 4);
sample();
sample();
sample();
sample(); // this will be executed
sample();
sample();
sample();
sample(); // this will be executed
The sampling function is different than throttling as throttling limits the execution of the function once in a given amount of time while sampling limits the execution by executing function once in a given number of calls.
To create a sampling function we can create a closure that will track how many times the function has been called and once it reaches the count, execute the input function and reset the counter.
function sampler(fn, count, context){
let counter = 0;
return function(...args){
// set the counters
let lastArgs = args;
context = this ?? context;
// invoke only when number of calls is equal to the counts
if(++counter !== count) return;
fn.apply(context, args);
counter = 0;
};
}
function message(){
console.log("hello");
}
const sample = sampler(message, 4);
sample();
sample();
sample();
sample(); // hello
sample();
sample();
sample();
sample(); // hello