Debounce & Throttle
Event seperti scroll, resize, dan input bisa fire ratusan kali per detik. Tanpa kontrol, handler yang berat akan membuat halaman tidak responsif.
Debounce
Menunda eksekusi sampai user berhenti melakukan aksi selama periode tertentu.
Use case: search input — tunggu user selesai mengetik sebelum API call.
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const search = debounce((query) => {
fetch("/api/search?q=" + query);
}, 300);
Throttle
Membatasi eksekusi maksimal sekali per interval.
Use case: scroll event — update posisi maksimal 60x per detik.
function throttle(fn, interval) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= interval) {
lastTime = now;
fn.apply(this, args);
}
};
}
window.addEventListener("scroll", throttle(updatePosition, 16));