Skip to the code

A search box that answers at once

The tea shop's search box filters 5,000 teas on every key press. The filter takes 150 ms, so each letter shows up late, and the page's Interaction to Next Paint is poor. Write respondToInput(input, { update, work }). It listens for input events on the input element, and for each one calls update(value) at once, inside the event handler, with the box's value. That's the cheap part, like a heading that says Results for "mi", which the shopper should see in the next frame.

Then it runs work(value) after the next paint. From the handler, ask for an animation frame, and from inside the frame callback queue a task with a 0 ms setTimeout. work runs in that task. Only the latest input's work runs: when another input event comes before an earlier one's work has run, the earlier work is dropped, even if its frame has passed and only its timeout is left.

respondToInput returns a function that stops it: the listener is removed, and work that's still waiting doesn't run. This isn't a debounce (the JavaScript problem debounce waits until typing stops for a while): work runs as soon as the browser has painted, with the newest value.

const stop = respondToInput(document.querySelector("#search"), {
  update: (value) => (heading.textContent = 'Results for "' + value + '"'),
  work: (value) => showTeas(filterTeas(allTeas, value)), // 150 ms, after the paint
});

What the tests check

  1. updates at once, inside the event handler, and works later
    const clock = useFakeTimers();
    const input = document.querySelector("#search");
    const seen = [];
    respondToInput(input, {
      update: (value) => seen.push("update " + value),
      work: (value) => seen.push("work " + value),
    });
    input.value = "mint";
    fire(input, "input");
    expect(seen).toEqual(["update mint"]);
    await clock.runAllAsync();
    expect(seen).toEqual(["update mint", "work mint"]);
    
  2. runs the work in a task after the next frame
    const clock = useFakeTimers();
    const input = document.querySelector("#search");
    const order = [];
    respondToInput(input, {
      update: () => order.push("update"),
      work: () => order.push("work at " + clock.now()),
    });
    input.value = "oolong";
    fire(input, "input");
    requestAnimationFrame(() => order.push("frame"));
    await clock.runAllAsync();
    expect(order).toEqual(["update", "frame", "work at 16"]);
    
  3. only the latest input's work runs
    const clock = useFakeTimers();
    const input = document.querySelector("#search");
    const updates = [];
    const works = [];
    respondToInput(input, { update: (value) => updates.push(value), work: (value) => works.push(value) });
    for (const value of ["m", "mi", "min", "mint"]) {
      input.value = value;
      fire(input, "input");
    }
    await clock.runAllAsync();
    expect(updates).toEqual(["m", "mi", "min", "mint"]);
    expect(works).toEqual(["mint"]);
    
  4. drops earlier work even when only its timeout is left
    const clock = useFakeTimers();
    const input = document.querySelector("#search");
    const works = [];
    respondToInput(input, { update: () => {}, work: (value) => works.push(value + " at " + clock.now()) });
    input.value = "gr";
    fire(input, "input");
    // The next key press is handled in the same frame, after the search box's frame callback.
    requestAnimationFrame(() => {
      input.value = "green";
      fire(input, "input");
    });
    await clock.runAllAsync();
    expect(works).toEqual(["green at 32"]);
    
  5. inputs that come in different frames each get their work
    const clock = useFakeTimers();
    const input = document.querySelector("#search");
    const works = [];
    respondToInput(input, { update: () => {}, work: (value) => works.push(value + " at " + clock.now()) });
    input.value = "g";
    fire(input, "input");
    await clock.runAllAsync();
    clock.spend(20);
    input.value = "green";
    fire(input, "input");
    await clock.runAllAsync();
    expect(works).toEqual(["g at 16", "green at 48"]);
    
  6. the function it returns stops listening and drops waiting work
    const clock = useFakeTimers();
    const input = document.querySelector("#search");
    const seen = [];
    const stop = respondToInput(input, {
      update: (value) => seen.push("update " + value),
      work: (value) => seen.push("work " + value),
    });
    input.value = "mint";
    fire(input, "input");
    stop();
    input.value = "mint tea";
    fire(input, "input");
    await clock.runAllAsync();
    expect(seen).toEqual(["update mint"]);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).