Skip to content

Instantly share code, notes, and snippets.

@KennFatt
Last active April 23, 2021 06:42
Show Gist options
  • Save KennFatt/7c7ed3651433cfed55d4faae049840e3 to your computer and use it in GitHub Desktop.
Save KennFatt/7c7ed3651433cfed55d4faae049840e3 to your computer and use it in GitHub Desktop.
In-depth JS Runtime Environment: Microtask vs. Task
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!");
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...");
@KennFatt
Copy link
Author

KennFatt commented Apr 23, 2021

Output:

microtask_task.js

Main thread running...
10! is equal to:  3628800
Main thread is now empty...
microtask#main
microtask#1
microtask#2
microtask#main#children
task#main
task#1
task#2
task#main#children

execution_sequence.js

Starting the program...
call stack is now empty!
microtask#1
microtask#2
Task#1
task#3
task#2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment