Created
April 27, 2023 16:12
-
-
Save epreston/4fac9f71bc3be0ea8e9c4de9d668608f to your computer and use it in GitHub Desktop.
queueMicrotask - usage in synthetic events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.