Skip to content

Instantly share code, notes, and snippets.

@epreston
Last active April 28, 2023 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save epreston/9bb41fbbf8b34c3b11c1b07f399480bf to your computer and use it in GitHub Desktop.
Save epreston/9bb41fbbf8b34c3b11c1b07f399480bf to your computer and use it in GitHub Desktop.
wait for idle promise - runs async right before paint - safari fallback
const idleOptions = { timeout: 500 };
const request = window.requestIdleCallback || window.requestAnimationFrame;
const cancel = window.cancelIdleCallback || window.cancelAnimationFrame;
const resolveWhenIdle = {
request,
cancel,
promise: (num) => new Promise((resolve) => request(resolve, Object.assign({}, idleOptions, num))),
};
@epreston
Copy link
Author

It's different from setTimeout (runs async after paint) or microtask (sync code that's pushed to the end of the current work).

It uses one of the following functions because requestIdleCallback is not supported in Safari.

  • requestIdleCallback (no sooner than the next pass through the event loop)
  • requestAnimationFrame (runs async right before next paint).

This provides a consistent interface between the two.

It is used to introduce delays to allow animations or DOM updates to render as states change.

Examples:

await resolveWhenIdle.promise(50)

await resolveWhenIdle.promise({
  timeout: 50,
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment