Last active
March 24, 2017 08:37
-
-
Save DadgadCafe/80bd786da51bab44b1258a1f14d7b9c5 to your computer and use it in GitHub Desktop.
detailed demo of event priority.
This file contains hidden or 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
(function () { | |
setImmediate(function () { | |
console.log(6) // run macro-task | |
}) | |
setTimeout(function () { | |
console.log(8) // 4ms delay | |
}, 0) | |
Promise | |
.resolve() | |
.then(() => {console.log(3)}) // priority after nextTick | |
.then(() => {console.log(4)}) // add to current micro-task & run | |
.then(() => new Promise(resolve => { // add to current micro-task & run | |
process.nextTick(() => { // add to current micro-task & run | |
resolve(5) | |
}) | |
})) | |
.then((v) => {console.log(v)}) | |
.then(() => new Promise(resolve => { // add to current micro-task & run | |
setImmediate(() => { // add to macro-task, current micro-task clear | |
resolve(7) // added after 6, FIFO | |
}) | |
})) | |
.then((v) => {console.log(v)}) | |
.then(() => new Promise(resolve => { | |
setTimeout(() => { | |
resolve(9) // run after 8, FIFO | |
}, 0) | |
})) | |
.then((v) => {console.log(v)}) | |
process.nextTick(() => { | |
console.log(2) // done main script, run micro-task | |
}) | |
console.log(1) // main script | |
})() | |
// queue: | |
// macro-task(task): | |
// main script > setTimeout > setInterval > setImmediate > I/O > UI rendering | |
// micro-task(jobs): | |
// process.nextTick > Promise > Object.observe > MutationObserver | |
// run program in order: | |
// script -> micro-task -> macro-task -> micro-task -> macro-task ... -> end | |
// FYI: https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/ | |
// http://stackoverflow.com/questions/25915634/difference-between-microtask-and-macrotask-within-an-event-loop-context |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment