Middle
What is the difference between regular tasks and micro-tasks?
sobes.tech AI
Answer from AI
Regular tasks (macrotasks) are executed after the current Event Loop macro cycle completes. Microtasks are executed after the current function finishes but before the next macro cycle begins.
Regular tasks include: scripts, timers (setTimeout, setInterval), input/output operations.
Microtasks include: promises (.then(), .catch(), .finally()), process.nextTick(), queueMicrotask(), MutationObserver (in browsers).
Example execution order:
console.log('Start'); // Regular task 1 (initial script)
setTimeout(() => {
console.log('setTimeout'); // Regular task 2
}, 0);
Promise.resolve()
.then(() => {
console.log('Promise 1'); // Microtask 1
})
.then(() => {
console.log('Promise 2'); // Microtask 2
});
process.nextTick(() => {
console.log('nextTick'); // Microtask 3 (executes before promises)
});
console.log('End'); // Regular task 1 (script continuation)
Output order:
Start
End
nextTick
Promise 1
Promise 2
setTimeout
Main differences:
| Characteristic | Regular tasks (Macrotasks) | Microtasks |
|---|---|---|
| Execution queue | Executed after all microtasks of the current cycle. | Executed after the current operation but before the next regular task. |
| Sources | setTimeout, setInterval, I/O, UI rendering. |
Promise.then, process.nextTick, queueMicrotask. |
| Priority | Lower | Higher |