Skip to the code

Run work after the next paint

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");
});

What the tests check

  1. waits for the next frame
    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);
    
  2. resolves in a task after the frame, not inside it
    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"]);
    
  3. resolves at that frame's time, not a frame later
    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]);
    
  4. waits for the next frame from wherever the clock is
    const clock = useFakeTimers();
    clock.spend(36);
    let at = null;
    afterNextPaint().then(() => (at = clock.now()));
    await clock.runAllAsync();
    expect(at).toBe(48);
    
  5. on a hidden page, resolves after a 0 ms timeout without asking for a frame
    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);
    

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