Prevent expensive functions from running too often and hurting performance.
Debouncing ensures a function runs only after a specified delay has passed since the last event.
function debounce(fn, delay) {let timer;return (...args) => {clearTimeout(timer);timer = setTimeout(() => fn(...args), delay);};}
input.addEventListener("input", debounce(handleSearch, 300));
Throttling ensures a function runs at most once every fixed interval, no matter how often the event fires.
function throttle(fn, interval) {let lastTime = 0;return (...args) => {const now = Date.now();if (now - lastTime >= interval) {lastTime = now;fn(...args);}};}
window.addEventListener("scroll", throttle(handleScroll, 200));
🧠 Key idea: Run regularly, but not too often.
lodash.debounce, lodash.throttle) in production