In this lesson, the dryer got a door sensor that sends a ping every time the door moves. One door closing sent four pings, and the house program printed four reports. You debounced the sensor, so the program now waits until the door goes quiet and then sends one report.
Key Points
- A debounce function takes a callback and a delay, and returns a new function. Each call of that function does two things, right away: it cancels the waiting timer with
clearTimeout(), then starts a new one withsetTimeout(). - Only the last timer gets to finish. The callback runs once the calls have stopped for the whole delay.
- The returned function is a closure: it keeps reaching the
timervariable ofdebounce(), even afterdebounce()has returned. Every call reaches the same variable, so each new timer replaces the last one, anddebounce()works for any callback. - On the first call,
timeris stillundefined, so there’s nothing to cancel.clearTimeout(undefined)does nothing. - With four pings in three tenths of a second and a delay of 500 milliseconds, the report prints once, at about 0.8 seconds: half a second after the last ping.
- Throttling is a related pattern. It doesn’t wait for the quiet: while the calls keep coming, it still runs the callback, at most once per set time.
The Final Code
Four timeouts at 0, 100, 200 and 300 milliseconds stand in for the door sensor, and each one calls the debounced onPing():
debounced_door.mjs
const start = Date.now();
const seconds = () => ((Date.now() - start) / 1000).toFixed(1);
function report() {
console.log(`${seconds()}s Dryer door closed`);
}
function debounce(callback, delay) {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(callback, delay);
};
}
const onPing = debounce(report, 500);
for (const ms of [0, 100, 200, 300]) {
setTimeout(onPing, ms);
}
Run it with Node, and it prints one report:
$ node debounced_door.mjs
0.8s Dryer door closed
Without debounce(), with setTimeout(report, ms) in the loop, the same four pings print four reports, at 0.0, 0.1, 0.2 and 0.3 seconds.
Next comes Exercise: Nag About the Laundry, the course’s first coding exercise. You’ll put the dryer’s alerts together: a door report that waits for the door to settle, and a nag that keeps going until someone opens the door. You write and run the code in your browser, and tests check it. The exercise’s Contents tab explains how coding exercises work.