Last active
April 23, 2021 06:42
-
-
Save KennFatt/7c7ed3651433cfed55d4faae049840e3 to your computer and use it in GitHub Desktop.
In-depth JS Runtime Environment: Microtask vs. Task
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
console.log("Starting the program..."); | |
setTimeout(() => { | |
console.log("Task#1"); | |
setTimeout(() => console.log("task#2")); | |
}); | |
queueMicrotask(() => { | |
console.log("microtask#1"); | |
queueMicrotask(() => console.log("microtask#2")); | |
}); | |
setTimeout(() => console.log("task#3")); | |
console.log("call stack is now empty!"); |
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
const doWork = () => { | |
queueMicrotask(() => { | |
console.log("microtask#1"); | |
}); | |
setTimeout(() => { | |
console.log("task#1"); | |
}, 0); | |
queueMicrotask(() => { | |
console.log("microtask#2"); | |
}); | |
setTimeout(() => { | |
console.log("task#2"); | |
}, 0); | |
let result = 1; | |
for (let i = 2; i <= 10; ++i) { | |
result *= i; | |
} | |
return result; | |
}; | |
console.log("Main thread running..."); | |
queueMicrotask(() => { | |
console.log("microtask#main"); | |
queueMicrotask(() => { | |
console.log("microtask#main#children"); | |
}); | |
}); | |
setTimeout(() => { | |
console.log("task#main"); | |
setTimeout(() => { | |
console.log("task#main#children"); | |
}); | |
}, 0); | |
console.log("10! is equal to: ", doWork()); | |
console.log("Main thread is now empty..."); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output:
microtask_task.js
execution_sequence.js