Sub topic 4
Keeping this and Arguments Intact
A debounced function sits between the caller and your real handler. The caller thinks it is calling your handler, but it is really calling a wrapper. That wrapper must hand two things to the real function when it finally runs: the this value the caller used and the arguments the caller passed. If either one gets lost, the handler runs at the right time and does the wrong thing.
This chapter assumes you know how this is set for regular functions versus arrow functions, how rest parameters work, and what Function.prototype.apply does. It builds on the trailing-edge debounce from the previous chapter.
Where this and Arguments Get Lost
Here is the trailing-edge debounce again:
function debounce(fn, wait) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
}Two hand-offs happen in this code, and each one can go wrong.
- The caller calls the wrapper. The wrapper is a regular
function, so it gets its ownthisfrom the call site:obj.method()setsthistoobj, and an event listener sets it to the element. The rest parameter...argscollects the arguments into a real array. - Later, the timer fires and calls the callback. The callback is an arrow function, so it has no
thisof its own. It uses thethisof the wrapper call that scheduled it.argsis the closure variable from that same call.
Then fn.apply(this, args) calls the original function with both values restored.
A Runnable Demonstration
Debouncing an object method shows the problem clearly, because the method reads this. Save this as context.js and run it with node context.js:
'use strict';
function debounce(fn, wait) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
}
const counter = {
label: 'clicks',
report(count) {
console.log(`${this.label}: ${count}`);
},
};
counter.report = debounce(counter.report, 100);
counter.report(1);
counter.report(2);
counter.report(3);
// After 100 ms, prints: clicks: 3The wrapper is stored on counter, so counter.report(3) sets this to counter inside the wrapper. The arrow callback keeps that value, and apply passes it on. Only the last call's arguments survive, because each call cancels the timer that the earlier call scheduled, along with that call's closure.
Three Common Ways to Break It
Mistake 1: The wrapper is an arrow function
function debounceBroken(fn, wait) {
let timerId;
return (...args) => {
clearTimeout(timerId);
timerId = setTimeout(() => fn.apply(this, args), wait);
};
}An arrow function's this comes from where the arrow is defined. Here that is the body of debounceBroken, which was called as a plain function. When counter.report(3) calls the wrapper, the counter receiver is ignored. In strict mode or an ES module, this is undefined and this.label throws a TypeError. In a sloppy script, this is the global object and the output is undefined: 3.
Mistake 2: The timer callback is a regular function
function debounceBroken2(fn, wait) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(function () {
fn.apply(this, args);
}, wait);
};
}The wrapper receives the right this, but the inner function gets a new one from the timer. In browsers that is window. In Node it is the Timeout object. Either way the caller's this is gone. If you also switched args to arguments here, you would get the timer callback's own empty arguments object rather than the caller's.
Mistake 3: Dropping the arguments
timerId = setTimeout(() => fn.call(this), wait);this survives, but fn receives no arguments. An input handler that reads event.target.value will then throw, because event is undefined.
| Wrapper | Timer callback | `this` inside `fn` | Arguments inside `fn` |
|---|---|---|---|
| `function` | arrow, `fn.apply(this, args)` | caller's `this` | last call's arguments |
| arrow | arrow | `this` of the code that called `debounce` | last call's arguments |
| `function` | `function`, `fn.apply(this, args)` | `window` or Node `Timeout` | last call's arguments |
| `function` | arrow, `fn.call(this)` | caller's `this` | none |
The Pre-ES2015 Pattern
Older libraries, including Lodash's source, were written before arrow functions and rest parameters existed. They save the values in variables before scheduling:
function debounceES5(fn, wait) {
var timerId;
return function () {
var context = this;
var args = arguments;
clearTimeout(timerId);
timerId = setTimeout(function () {
fn.apply(context, args);
}, wait);
};
}This works the same way as the modern version. context and args are ordinary closure variables, so the inner regular function's own this doesn't matter. When you read older code, var context = this is the line that does the job the arrow function does in the modern version.
When Passing this Doesn't Matter, and When It Does
If the function you debounce is an arrow function, passing this has no effect. An arrow function ignores the this given to apply. The wrapper still has to forward it, because it can't know what kind of function it was given.
Regular functions used as DOM listeners depend on it. addEventListener calls the listener with this set to the element:
const input = document.querySelector('#search');
input.addEventListener('input', debounce(function () {
console.log('Search for:', this.value);
}, 300));This works only because the wrapper is a regular function that receives the input element as this and forwards it. With Mistake 1 or Mistake 2, this.value would be undefined.
Class methods are a related case. Assigning the wrapper in the constructor gives each instance its own timer, and calls go through the instance, so this is correct:
class Autosave {
constructor(name) {
this.name = name;
this.save = debounce(this.save, 500);
}
save(text) {
console.log(`${this.name} saved: ${text}`);
}
}
const doc = new Autosave('notes');
doc.save('a');
doc.save('ab');
// After 500 ms, prints: notes saved: abEvent Objects Change After Dispatch
Forwarding the arguments is not always enough when the argument is a DOM event, because the event object changes after dispatch. A debounced handler runs after the event has finished dispatching, and by then some of its properties have changed:
event.currentTargetisnullonce dispatch ends. Readevent.target, or readthisin a regular function.event.preventDefault()has no effect by then. The browser has already performed the default action. If you need to prevent it, callpreventDefault()in a listener that runs right away, outside the debounce.- Old React versions (16 and earlier) pooled synthetic events and cleared their fields after the handler returned. React 17 removed pooling, but the habit below is still safe.
To avoid all three, read the values you need when the event fires and debounce a function that takes plain data:
const input = document.querySelector('#search');
const search = debounce((query) => {
console.log('Search for:', query);
}, 300);
input.addEventListener('input', (event) => {
search(event.target.value);
});This version is also easier to test, because search takes a string instead of an event.
What Happens to Return Values
The debounced wrapper returns undefined, because fn has not run yet when the caller gets control back. Code like const result = debouncedFn(x) always gets undefined. If the caller needs the result, have fn handle it, for example by updating state or resolving a promise. The flush method covered in a later chapter can also run the pending call right away and return its result.
Exercises
Exercise
A teammate writes const debounce = (fn, wait) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn.apply(this, a), wait); }; }; and uses it as button.addEventListener('click', debounce(function () { this.disabled = true; }, 200));. What happens when the button is clicked, and what is the smallest fix?
Show answer
The returned wrapper is an arrow function, so its this comes from the module scope (undefined in an ES module) rather than from the button. The handler then runs with this undefined and throws a TypeError on this.disabled, or sets a stray global in a sloppy script. The smallest fix is to make the returned wrapper a regular function: return function (...a) { ... }. The arrow inside setTimeout can stay.
Exercise
Why does debounce((event) => console.log(event.currentTarget.id), 300) used as an input listener log a TypeError instead of the input's id?
Show answer
The debounced function runs 300 ms after the event finishes dispatching. By then event.currentTarget has been reset to null, so reading .id throws. Use event.target.id, or better, read the id when the event fires and pass it to a debounced function that takes plain data.
Exercise
Write a variant debounceBatch(fn, wait) that calls fn once after the burst ends, passing an array that holds the arguments array of every call in the burst, with the caller's this from the last call.
Show answer
function debounceBatch(fn, wait) { let timerId; let batch = []; return function (...args) { batch.push(args); clearTimeout(timerId); timerId = setTimeout(() => { const calls = batch; batch = []; fn.call(this, calls); }, wait); }; } The arrow callback keeps the this of the last call, and batch is reset before fn runs so that calls made while fn is running start a new batch.