Careeroza
Debounce & Throttle
Debounce
Debounce waits until calls stop for a given time, then runs once. Use it for search-as-you-type and window resize handlers.
Example
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
const search = debounce((q) => console.log("searching for", q), 50);
search("j"); search("ja"); search("jav"); search("java"); // only the last runsOutput
searching for java
Throttle
Throttle runs at most once per time window. Use it for scroll and mousemove handlers.
Example
function throttle(fn, ms) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= ms) {
last = now;
fn(...args);
}
};
}
const log = throttle((i) => console.log("handled event", i), 1000);
for (let i = 1; i <= 5; i++) log(i); // only the first call in this second runsOutput
handled event 1
Try It in the Browser
Example
Type quickly: the debounced counter updates only after you pause.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input id="q" placeholder="Type fast...">
<p>Input events: <b id="raw">0</b> · Debounced searches: <b id="deb">0</b></p>
<script>
const debounce = (fn, ms) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; };
let raw = 0, deb = 0;
const run = debounce(() => (document.getElementById("deb").textContent = ++deb), 400);
document.getElementById("q").addEventListener("input", () => {
document.getElementById("raw").textContent = ++raw;
run();
});
</script>
</body>
</html>Result