Skip to content

Instantly share code, notes, and snippets.

@epreston
Created April 27, 2023 16:12
Show Gist options
  • Save epreston/4fac9f71bc3be0ea8e9c4de9d668608f to your computer and use it in GitHub Desktop.
Save epreston/4fac9f71bc3be0ea8e9c4de9d668608f to your computer and use it in GitHub Desktop.
queueMicrotask - usage in synthetic events
// see: https://twitter.com/diegohaz/status/1530662445240426496
const anotherElement = document.querySelector('#anotherElement');
function onClick() {
// BAD - Focus will fire on another element before the
// click event finishes bubbling. You may get events
// in the wrong order on parent elements.
anotherElement.focus();
// GOOD - By queuing a microtask, the click event will be
// completely done when the focus event fires.
queueMicrotask(() => {
anotherElement.focus();
});
}
@epreston
Copy link
Author

A promise that resolves immediately is the same as queueMicrotask:

Promise.resolve().then(callback)

setTimeout is totally different. It will happen after the browser paint.

A microtask is a kind of synchronous code executed at the end of the current running stack and synthetic events. Native even bubbling occurs after.

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