What is the difference between debouncing and throttling?
Both of these limit how often a function runs when it is called again and again, and the difference between them is exactly when the function is allowed to run.
Debouncing waits for the calls to stop. Every new call cancels the waiting one and starts the clock again, so the function runs only once, after the last call, and it receives the arguments from that last call. The classic example is a search box that queries the server only once the user has stopped typing.
Throttling caps the rate. The function runs immediately on the first call, and then any further calls inside the same window are dropped until that window ends. The classic example is a scroll handler that has to do work on every scroll event but is allowed to do it only a few times a second.
// Debounce: run only after the calls stop.
function debounce(fn, waitMs) {
var timer = null;
return function () {
var args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(null, args);
}, waitMs);
};
}
// Throttle: run at most once per interval.
function throttle(fn, waitMs) {
var blocked = false;
return function () {
if (blocked) {
return;
}
blocked = true;
fn.apply(null, arguments);
setTimeout(function () {
blocked = false;
}, waitMs);
};
}
That difference shows up clearly in the timing. A debounced function does not run at all until the calls stop, so it never runs in the middle of a burst of events. A throttled function runs at the start of the burst and then stays quiet for the rest of that window.
There is also a trailing version of throttle, which runs the function one more time at the end of the window with the most recent arguments. That is often what you actually want for something like a scroll handler, because you also want the final position to be handled.