Wait for a Pause With Debounce

Sam’s recipe box has a Filter field that filters every time its text changes. Typing “lentil” runs the filter and redraws the whole list six times, once per partial word, such as “le” or “len”. With four recipes, that’s fine, since the list narrows as Sam types at no visible cost. With hundreds of recipes or an old tablet, though, every keystroke waits on a redraw. Sam’s box should wait for a pause, so the field stays smooth as the box grows.

In this lesson, you’ll write a function that waits for a pause in the typing and then runs once, with the last text. First, you’ll learn a second way to repeat a timer, in which your own code starts the next timeout, and when to choose it over setInterval().

Debouncing rests on the same move of starting and restarting the next timeout yourself. A reminder shows that move more plainly, so you’ll start with the stir reminder from Schedule and Cancel Timers.

Repeat by Chaining Timeouts

The stir reminder used setInterval(), which calls its callback every time the delay passes. That’s fine while the callback is quick. Say the reminder also redraws the recipe list, and the redraw is slow on Sam’s old tablet. What happens to the gaps between reminders then?

The snippet below stands in for that slow redraw with the handwritten busy wait from Schedule and Cancel Timers. Each reminder runs it for 300 milliseconds. The interval’s delay is 200 milliseconds, and each reminder logs when it started, rounded to the nearest 100 milliseconds. Open a new tab at about:blank, open its Console, and keep it open for the whole lesson. Type the snippet as one entry, with Shift+Enter between the lines:

Language: JavaScript
function stirWithInterval() {
  const startedAt = Date.now();
  let reminders = 0;
  const id = setInterval(() => {
    reminders += 1;
    const ms = Date.now() - startedAt;
    const at = Math.round(ms / 100) * 100;
    console.log(`Stir ${reminders} at about ${at} ms`);
    if (reminders === 3) {
      clearInterval(id);
    }
    const began = Date.now();
    while (Date.now() - began < 300) {}
  }, 200);
}
stirWithInterval();

Press Enter, and after the Console’s undefined echo, three lines arrive within about a second:

Language: Program Output
Stir 1 at about 200 ms
Stir 2 at about 500 ms
Stir 3 at about 800 ms

In this run, the reminders came about 300 milliseconds apart, with no 200-millisecond pause between them. The interval counts its 200 milliseconds whether or not the callback has finished, so the next reminder was already due when the redraw ended, and it ran soon after. A slow enough callback leaves the page almost no quiet time.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.