Debounce vs Throttle
Rate-limiting functions — two common strategies
function debounce(fn, delay) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
function throttle(fn, interval) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= interval) {
lastCall = now;
fn.apply(this, args);
}
};
}
const log = label => value => console.log(label, value);
const debounced = debounce(log("debounced:"), 300);
const throttled = throttle(log("throttled:"), 300);
// Simulate rapid events
[0, 50, 100, 150, 200, 500, 900].forEach((ms, i) => {
setTimeout(() => {
debounced(i);
throttled(i);
}, ms);
});