Debounce and throttle
Debounce waits until the noise stops (search inputs). Throttle guarantees a steady rate (scroll, resize).
#performance#events#timers
javascript
function debounce(fn, ms = 300) {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), ms);
};
}
function throttle(fn, ms = 200) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= ms) {
last = now;
fn(...args);
}
};
}