Last active
November 14, 2019 17:30
-
-
Save ackvf/45f397a33cc9f0302019e3e47c838688 to your computer and use it in GitHub Desktop.
Understanding the Event Loop
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
function callback(arg) { | |
setTimeout(console.log, 0, arg, ' # 4 timeout '); | |
setImmediate(console.log, arg, ' # 5 immediate'); | |
process.nextTick(console.log, arg, ' # 2 nextTick '); | |
(async () => { await undefined; console.log(arg, ' # 3 await '); })(); | |
console.log(arg, '# 1 sync '); | |
} | |
setTimeout(callback, 0, ' # 4 timeout '); | |
setImmediate(callback, ' # 5 immediate'); | |
process.nextTick(callback, ' # 2 nextTick '); | |
(async () => { await undefined; callback(' # 3 await '); })(); | |
callback('# 1 sync '); | |
/* Result: | |
# 1 sync # 1 sync | |
# 2 nextTick # 1 sync | |
# 1 sync # 2 nextTick | |
# 2 nextTick # 2 nextTick | |
# 3 await # 1 sync | |
# 1 sync # 3 await | |
# 2 nextTick # 3 await | |
# 3 await # 3 await | |
# 3 await # 2 nextTick | |
# 4 timeout # 1 sync | |
# 4 timeout # 2 nextTick | |
# 4 timeout # 3 await | |
# 1 sync # 4 timeout | |
# 2 nextTick # 4 timeout | |
# 3 await # 4 timeout | |
# 5 immediate # 1 sync | |
# 5 immediate # 2 nextTick | |
# 5 immediate # 3 await | |
# 1 sync # 5 immediate | |
# 2 nextTick # 5 immediate | |
# 3 await # 5 immediate | |
# 4 timeout # 5 immediate | |
# 4 timeout # 4 timeout | |
# 5 immediate # 4 timeout | |
# 5 immediate # 5 immediate | |
*/ |
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
// https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick | |
// https://javascript.info/event-loop | |
setImmediate(console.log, 'immediate') | |
setTimeout(console.log, 0, 'timeout') | |
queueMicrotask(() => console.log('microtask')) | |
;(async () => { await undefined; console.log('await') })() | |
new Promise(resolve => { console.log('promise'); resolve('promised') }).then(console.log) | |
process.nextTick(console.log, 'nextTick') | |
console.log('sync') | |
/* Result: | |
promise | |
sync | |
nextTick | |
microtask | |
await | |
promised | |
timeout | |
immediate | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment