When a shopper taps "Add to basket", the tea shop should show the new count in the very next frame, and only then save the basket and send analytics. Write afterNextPaint(), which returns a promise that resolves just after the next paint, so await afterNextPaint() moves the rest of a handler past it.
The browser paints right after it runs a frame's requestAnimationFrame callbacks, so resolving inside one of them is too early: the work would still run before the paint. Call requestAnimationFrame, and from inside its callback queue a task (a 0 ms setTimeout works in every browser) that resolves the promise. That task runs as soon as the frame is rendered, not a frame later.
A hidden page isn't rendered, so it gets no frames until it's shown again: browsers pause requestAnimationFrame in background tabs. When document.visibilityState is "hidden", don't ask for a frame: resolve in a 0 ms setTimeout.
basketButton.addEventListener("click", async () => {
showBasketCount(basket.length + 1); // painted in the next frame
await afterNextPaint();
saveBasket(); // runs after that paint, in a task of its own
sendAnalytics("add-to-basket");
});
const clock = useFakeTimers();
let done = false;
afterNextPaint().then(() => (done = true));
await flush();
expect(done).toBe(false);
await clock.tickAsync(15);
expect(done).toBe(false);
await clock.tickAsync(1);
expect(done).toBe(true);
const clock = useFakeTimers();
const order = [];
afterNextPaint().then(() => order.push("after the paint"));
requestAnimationFrame(() => {
order.push("frame");
Promise.resolve().then(() => order.push("still in the frame"));
});
await clock.runAllAsync();
expect(order).toEqual(["frame", "still in the frame", "after the paint"]);
const clock = useFakeTimers();
const times = [];
afterNextPaint().then(() => times.push(clock.now()));
afterNextPaint().then(() => times.push(clock.now()));
await clock.runAllAsync();
expect(times).toEqual([16, 16]);
const clock = useFakeTimers();
clock.spend(36);
let at = null;
afterNextPaint().then(() => (at = clock.now()));
await clock.runAllAsync();
expect(at).toBe(48);
const clock = useFakeTimers();
setVisibility("hidden");
let frames = 0;
const realFrame = requestAnimationFrame;
globalThis.requestAnimationFrame = (callback) => {
frames += 1;
return realFrame(callback);
};
clock.spend(5);
let at = null;
afterNextPaint().then(() => (at = clock.now()));
await clock.runAllAsync();
expect(at).toBe(5);
expect(frames).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 Run work after the next paint. 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.