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

epreston commented Apr 27, 2023

For for synthetic events like the ones in React, A microtask is essentially sync code that's pushed to the end of the current work (as if you've written it at the end of the script).

It's different from setTimeout (runs async after paint) and requestAnimationFrame (runs async right before paint).

Native event bubbling runs after microtasks, so you would instead use queueBeforeEvent helper in this gist: https://gist.github.com/epreston/c516fe61be14960265fd524ebcecc97c

@epreston
Copy link
Author

FT4Ai_RWAAoMEVK

@epreston
Copy link
Author

@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