Debounce vs Throttle — hand-rolled
Build tiny debounce and throttle utilities. Practice trailing and leading variants and know when to pick each.
Overview
Goal: Control noisy events.
- Debounce: wait for quiet, then run once
- Throttle: run at most once per interval
- Leading vs trailing calls
- Tiny, readable helpers

Debounce (trailing)
Trailing debounce resets a timer on each event and runs once when things calm down.
// Debounce (trailing): run once after events stop
function debounce(fn, wait) {
let t = null;
return function (...args) {
clearTimeout(t);
t = setTimeout(function () {
fn.apply(null, args);
}, wait);
};
}
// Simulate rapid events: only the last triggers the call
const debouncedLog = debounce(function (msg) {
console.log("debounced:", msg);
}, 10);
for (let i = 0; i < 5; i++) {
setTimeout(function () {
debouncedLog("final after bursts");
}, i * 3);
}

All lessons in this course
- setTimeout, setInterval, and timer drift
- Debounce vs Throttle — hand-rolled
- Animation Timing — intro with time-based loops