Loading video player…

Debounce a Chatty Sensor

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 with setTimeout().
  • 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 timer variable of debounce(), even after debounce() has returned. Every call reaches the same variable, so each new timer replaces the last one, and debounce() works for any callback.
  • On the first call, timer is still undefined, 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():

Language: JavaScript Filename: 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:

Language: Shell
$ 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.

00:00 In the last video, you built a nag that repeats until Dev collects the laundry. Now the dryer gets a door sensor. Every time the door moves, the sensor sends a ping, a short signal to the house program.

00:13 The seconds helper from the nag stamps each line with the time since the start. The report function logs that the dryer door is closed. There’s no real sensor here, so four timeouts stand in for it.

00:26 Wren, a housemate, shuts the door, and it jiggles four times in three tenths of a second. Each timeout calls the report, as the sensor would on each ping.

00:37 Run it, and the report prints four times, about a tenth of a second apart. But Wren closed the door once. The house wants one report, sent once the door has stopped moving.

00:51 So the program needs to wait until the door goes quiet. Each ping cancels the waiting timer and starts a fresh half-second one, so only the last timer gets to finish.

01:02 A new function, debounce, takes a callback and a delay. Inside it, a variable called timer will hold the handle of the waiting timer. The debounce function returns a new function, and each call of that function does two things, right away.

01:19 First, it cancels the waiting timer. Then it starts a new one, which calls the callback once the delay has passed. You pass debounce the report and 500 milliseconds, half a second.

01:33 The function it returns is kept as onPing, and the four timeouts now call it, once per ping. Every ping reaches the same timer variable. That’s because the returned function is a closure: it keeps reaching the variables of debounce, even after debounce has returned.

01:51 So the timer stays with the function that uses it, and debounce works for any callback. On the first ping, timer is still undefined, so there’s nothing to cancel.

02:03 Four pings arrive, all within three tenths of a second, and the delay is half a second. So, how many times does the report print? Your turn: pause the video and predict the count.

02:20 Once, at about eight tenths of a second.

02:24 The timeline shows why. The first ping starts a half-second timer. A tenth of a second later, the second ping cancels it and starts a new one. The third ping does the same, and so does the fourth.

02:39 After the last ping, the door is quiet. Nothing cancels that last timer, so once half a second has passed, it runs, and the report prints.

02:50 This pattern is called debouncing. The name comes from switches, whose contacts bounce before they settle, like this door’s sensor. In this debounce, each call to onPing() runs right away, and only replaces the timer.

03:04 The report runs only after the calls have stopped for the whole delay.

03:10 You may also meet a related pattern, throttling. It doesn’t wait for the quiet: while the calls keep coming, it still runs the callback, at most once per set time.

03:21 That’s all you need about throttling for now.

03:25 You’ve turned a chatty door sensor into one report with a single timer variable. Every ping cancels its timer and starts a new one.

03:34 Next comes Exercise: Nag About the Laundry. 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.

Become a Member to join the conversation.