Debouncing waits for a pause before firing a function — ideal for search inputs. Throttling limits how often a function fires — ideal for scroll handlers. Both prevent performance problems from too-frequent events.
Throttle and Debounce
// Debounce — wait until typing stops
let timer;
$('#search').on('input', function() {
clearTimeout(timer);
timer = setTimeout(() => {
search($(this).val());
}, 300);
});
// Throttle — max once per 200ms
let last = 0;
$(window).on('scroll', function() {
if (Date.now() - last > 200) {
doSomething();
last = Date.now();
}
});