Throttling is used to control how frequently a function is executed. With throttling applied, the function runs immediately on the first call, and it can only be called after a certain time any subsequent calls within during that waiting period are ignored.
🔗 Throttle 🟡 Medium 🧩 Pattern – JavaScript Essentials
Related: Debounce with flush and cancel | Matrixread
What is debouncing?
Debouncing is a technique that ensures that a function is called only after certain time, if the function is called when the timer is running then the previous timer is cancelled and a new timer is started.
JavaScript Throttle with cancel
/**
* @callback func
* @param {number} wait
* @return {Function}
*/
export default function throttle(func, wait) {
let timerId = null;
function throttled(...args) {
if (!timerId) {
func.apply(this, args);
timerId = setTimeout(() => (timerId = null), wait);
}
}
throttled.cancel = () => {
clearTimeout(timerId);
timerId = null;
};
return throttled;
}Code language: JavaScript (javascript)