Skip to content

A way to run code before the next frame #10113

@jakearchibald

Description

@jakearchibald

What problem are you trying to solve?

Deferring code until the render steps, but before paint, is a good way to optimise code related to rendering. It allows you to avoid running code too frequently, and run it just in time.

What solutions exist today?

requestAnimationFrame() lets you schedule a callback for the render steps. This will be before next render unless the current point in the event loop is between requestAnimationFrame callbacks and paint, in which case the callback will run after the next paint.

A piece of code may not know which of these states the event loop is in, so requestAnimationFrame() cannot reliably be used to run code before the next paint.

How would you solve it?

Some way of knowing if requestAnimationFrame(callback) will run callback before the next paint, or after the next paint. This could be a boolean, or something which offers more insight into the current event loop position.

Anything else?

A current sort-of hack is:

let rafWillBeAfterPaint = false;

(async () => {
  while (true) {
    await new Promise(r => requestAnimationFrame(() => r()));
    rafWillBeAfterPaint = true;
    await new Promise(r => setTimeout(() => r(), 0));
    rafWillBeAfterPaint = false;
  }
})();

Although this isn't totally reliable, and doesn't feel great performance-wise.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions