Sometimes, we need to limit the number of method calls based on time. A throttling method is the way to go.
Code
/**
* @param {(...args:any[]) => any} func
* @param {number} wait
* @returns {(...args:any[]) => any}
*/
function throttle(func, wait) {
let blocked = false;
let lastArgs;
const caller = function() {
if (lastArgs) {
func.apply(this, lastArgs);
setTimeout(caller, wait);
lastArgs = undefined;
} else {
blocked = false;
}
};
return function(...args) {
if (!blocked) {
blocked = true;
func.apply(this, args); // leading vs trailing throttling.
setTimeout(caller, wait);
} else {
lastArgs = args;
}
};
}
const logger = (inp) => console.log(inp);
const throttledMethod = throttle(logger, 1000);
const button = document.createElement('button');
button.innerText = 'Throttle';
document.body.appendChild(button);
button.addEventListener('click', () => throttledMethod('Hello World!'));