Skip to content

Instantly share code, notes, and snippets.

@liuwenzhuang
Created October 23, 2020 08:53
Show Gist options
  • Save liuwenzhuang/0f2d75f4fc50e7320e4bd09cc8a0eb96 to your computer and use it in GitHub Desktop.
Save liuwenzhuang/0f2d75f4fc50e7320e4bd09cc8a0eb96 to your computer and use it in GitHub Desktop.
javascript microtasks and tasks
/**
* console order is:
* main call stack start
* main callback stack end
* Promise
* mutate
* setTimeout
*
* @see https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
* callback of Promise, MutationObserver(as microtasks) has higher privilege then setTimeout callback
*/
console.log('main call stack start')
setTimeout(function() {
console.log('setTimeout')
}, 0)
Promise.resolve().then(function() {
console.log('Promise')
})
new MutationObserver(function() {
console.log('mutate')
}).observe(document.body, {
attributes: true
})
document.body.setAttribute('data-random', Math.random())
console.log('main callback stack end')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment