Skip to the code

Render a long list in time slices

The tea shop's catalog has 3,000 teas, and building every row in one go takes 600 ms, a long task that freezes the page. Write renderInSlices(container, items, renderItem, options), which renders the rows a slice at a time, one slice per animation frame, and returns a promise. renderItem(item, index) builds one row and returns a DOM node. Add the rows to container in the items' order.

Do all the work in requestAnimationFrame callbacks, starting with the next frame. The first frame empties container, so its old rows stay until then and the page never shows an empty list for a frame. In each frame, read performance.now() as the slice starts, then render rows one after another until options.budget ms (8 when it isn't given) or more have passed, checking after each row, so a frame always renders at least one. If rows are left, ask for another frame. When the last row is in, resolve the promise with true. An empty list empties the container in the first frame and resolves true.

Starting a render into a container cancels the one already running there: it renders nothing more, and its promise resolves with false. The new render starts in the next frame and empties the container, the old render's rows included. Renders into different containers don't affect each other. If renderItem throws, stop that render and reject its promise with the error. Every row built before the error stays in the container.

const done = renderInSlices(menu, teas, (tea) => {
  const row = document.createElement("li");
  row.textContent = tea.name + ": " + tea.price;
  return row;
});
// About 8 ms of rows a frame, so the page keeps painting and answering taps.
await done; // true, or false if a new search started another render first

What the tests check

  1. renders a slice per frame, about 8 ms each, and resolves true when done
    const clock = useFakeTimers();
    const menu = document.querySelector("#menu");
    const teas = Array.from({ length: 10 }, (_, index) => "Tea " + (index + 1));
    const starts = [];
    let result = "pending";
    renderInSlices(menu, teas, (tea) => {
      starts.push(clock.now());
      clock.spend(3);
      return Object.assign(document.createElement("li"), { textContent: tea });
    }).then((value) => (result = value));
    await clock.runAllAsync();
    expect(result).toBe(true);
    // Three 3 ms rows pass the 8 ms budget, and the next frame carries on.
    expect(starts).toEqual([16, 19, 22, 32, 35, 38, 48, 51, 54, 64]);
    expect(Array.from(menu.children, (row) => row.textContent)).toEqual(teas);
    
  2. keeps the old rows until the first frame, then replaces them
    const clock = useFakeTimers();
    const menu = document.querySelector("#menu");
    const texts = () => Array.from(menu.children, (row) => row.textContent);
    let result = "pending";
    renderInSlices(menu, ["Green", "Mint"], (tea) => Object.assign(document.createElement("li"), { textContent: tea })).then((value) => (result = value));
    await flush();
    expect(texts()).toEqual(["Loading teas"]);
    expect(result).toBe("pending");
    await clock.runAllAsync();
    expect(texts()).toEqual(["Green", "Mint"]);
    expect(result).toBe(true);
    
  3. a slice stops once the budget is reached, and takes another budget
    const clock = useFakeTimers();
    const starts = { menu: [], reviews: [] };
    const build = (list) => (text) => {
      starts[list].push(clock.now());
      clock.spend(4);
      return Object.assign(document.createElement("li"), { textContent: text });
    };
    renderInSlices(document.querySelector("#menu"), ["a", "b", "c", "d", "e"], build("menu"));
    await clock.runAllAsync();
    // Two 4 ms rows reach 8 ms exactly, which ends the slice.
    expect(starts.menu).toEqual([16, 20, 32, 36, 48]);
    renderInSlices(document.querySelector("#reviews"), ["1", "2", "3", "4", "5", "6", "7"], build("reviews"), { budget: 20 });
    await clock.runAllAsync();
    expect(starts.reviews).toEqual([64, 68, 72, 76, 80, 96, 100]);
    
  4. a frame renders at least one row, however slow it is
    const clock = useFakeTimers();
    const starts = [];
    renderInSlices(document.querySelector("#menu"), ["Green", "Mint", "Oolong"], (tea) => {
      starts.push(clock.now());
      clock.spend(30);
      return Object.assign(document.createElement("li"), { textContent: tea });
    });
    await clock.runAllAsync();
    expect(starts).toEqual([16, 48, 80]);
    
  5. a new render into the same container cancels the old one
    const clock = useFakeTimers();
    const menu = document.querySelector("#menu");
    const built = [];
    const build = (tea) => {
      built.push(tea);
      clock.spend(3);
      return Object.assign(document.createElement("li"), { textContent: tea });
    };
    const results = [];
    renderInSlices(menu, Array.from({ length: 10 }, (_, index) => "Tea " + (index + 1)), build).then((value) => results.push("all teas " + value));
    await clock.tickAsync(16);
    expect(menu.children.length).toBe(3);
    renderInSlices(menu, ["Mint", "Mint tea", "Moroccan mint"], build).then((value) => results.push("mint teas " + value));
    await flush();
    expect(results).toEqual(["all teas false"]);
    await clock.runAllAsync();
    expect(results).toEqual(["all teas false", "mint teas true"]);
    expect(Array.from(menu.children, (row) => row.textContent)).toEqual(["Mint", "Mint tea", "Moroccan mint"]);
    expect(built).toEqual(["Tea 1", "Tea 2", "Tea 3", "Mint", "Mint tea", "Moroccan mint"]);
    
  6. renders into different containers side by side
    const clock = useFakeTimers();
    const menu = document.querySelector("#menu");
    const reviews = document.querySelector("#reviews");
    const build = (text) => {
      clock.spend(3);
      return Object.assign(document.createElement("li"), { textContent: text });
    };
    const teas = ["Green", "Mint", "Oolong", "Black", "White"];
    const notes = ["Smoky", "Fresh", "Floral"];
    const results = [];
    renderInSlices(menu, teas, build).then((value) => results.push("menu " + value));
    renderInSlices(reviews, notes, build).then((value) => results.push("reviews " + value));
    await clock.runAllAsync();
    expect(results.sort()).toEqual(["menu true", "reviews true"]);
    expect(Array.from(menu.children, (row) => row.textContent)).toEqual(teas);
    expect(Array.from(reviews.children, (row) => row.textContent)).toEqual(notes);
    
  7. an error in renderItem rejects the promise, and the rows built before it stay
    const clock = useFakeTimers();
    const menu = document.querySelector("#menu");
    let outcome = "pending";
    renderInSlices(menu, ["Green", "Mint", "", "Oolong"], (tea, index) => {
      if (!tea) throw new Error("Row " + index + " has no name");
      return Object.assign(document.createElement("li"), { textContent: tea });
    }).then(
      () => (outcome = "resolved"),
      (error) => (outcome = error.message),
    );
    await clock.runAllAsync();
    expect(outcome).toBe("Row 2 has no name");
    expect(Array.from(menu.children, (row) => row.textContent)).toEqual(["Green", "Mint"]);
    
  8. an empty list empties the container in the next frame and resolves true
    const clock = useFakeTimers();
    const menu = document.querySelector("#menu");
    let result = "pending";
    renderInSlices(menu, [], () => {
      throw new Error("There are no rows to build");
    }).then((value) => (result = value));
    await flush();
    expect(result).toBe("pending");
    expect(menu.children.length).toBe(1);
    await clock.runAllAsync();
    expect(result).toBe(true);
    expect(menu.children.length).toBe(0);
    

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).