Skip to content

Instantly share code, notes, and snippets.

@epreston
Created April 28, 2023 20:51
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/ad411854d74c05a447e92e611334e502 to your computer and use it in GitHub Desktop.
Save epreston/ad411854d74c05a447e92e611334e502 to your computer and use it in GitHub Desktop.
promise based delay - runs async after paint
function resolveAfter(ms) {
// intoduces a delay
return new Promise((resolve) => setTimeout(resolve, ms));
}
@epreston
Copy link
Author

Uses setTimeout (runs async after paint).

Different from:

  • requestIdleCallback (no sooner than the next pass through the event loop)
  • requestAnimationFrame (runs async right before next paint).
  • microtask (sync code that's pushed to the end of the current work).

Useful for ensuring DOM updates, animations, general script delays to allow other things to complete.

Examples:

await resolveAfter(1000);

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