patternjavascriptModeratepending
Pattern: Debounce and throttle for rate-limiting function calls
Viewed 0 times
debouncethrottlerate-limitscrollinputperformance
Problem
Event handlers (scroll, resize, input) fire too frequently, causing performance issues with expensive operations like API calls or DOM updates.
Solution
Debounce: Wait until calls stop, then execute once.
Throttle: Execute at most once per interval.
// Debounce - waits for pause in calls
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
// Throttle - executes at most once per interval
function throttle(fn, interval) {
let lastTime = 0;
return (...args) => {
const now = Date.now();
if (now - lastTime >= interval) {
lastTime = now;
fn(...args);
}
};
}
// Usage:
const debouncedSearch = debounce(query => fetchResults(query), 300);
input.addEventListener('input', e => debouncedSearch(e.target.value));
const throttledScroll = throttle(() => updatePosition(), 100);
window.addEventListener('scroll', throttledScroll);
Throttle: Execute at most once per interval.
// Debounce - waits for pause in calls
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
// Throttle - executes at most once per interval
function throttle(fn, interval) {
let lastTime = 0;
return (...args) => {
const now = Date.now();
if (now - lastTime >= interval) {
lastTime = now;
fn(...args);
}
};
}
// Usage:
const debouncedSearch = debounce(query => fetchResults(query), 300);
input.addEventListener('input', e => debouncedSearch(e.target.value));
const throttledScroll = throttle(() => updatePosition(), 100);
window.addEventListener('scroll', throttledScroll);
Why
Debounce is ideal for search inputs (wait for user to stop typing). Throttle is ideal for scroll/resize (maintain responsiveness with limited calls).
Revisions (0)
No revisions yet.