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
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);
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);
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]);
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]);
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"]);
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);
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"]);
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);
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).
I'm here to help with Render a long list in time slices. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.