The following ES6 Javascript code, helps to throttle function calls without discarding them. It uses a queue to keep track of all the function calls. We can use the reset method to reset the queue and the setTimeout() method.
const throttle = (fn, delay) => {
let timeout;
let noDelay = true;
let queue = [];
const start = () => {
if (queue.length) {
const {context, args} = queue.shift();
fn.apply(context, arguments);
timeout = setTimeout(start, delay);
} else {
noDelay = true;
}
};
const ret = (...args) => {
queue.push({
context: this,
args,
});
if (noDelay) {
noDelay = false;
start();
}
};
ret.reset = () => {
clearTimeout(timeout);
queue = [];
};
return ret;
};
/* Usage */
const print = (number) => {
console.log(`Hello World! ${number}`);
}
const test = throttle(print, 3000);
test(1);
test(2);
test(3);
// test.reset(); This will clear the queue and hence the above test case will only output the first line.
// Output:
// Hello World! 1
// Hello World! 2
// Hello World! 3