Micro tasks — execute immediately after current operation ⚡ Macro tasks — execute in next event loop cycle 🔄
// Micro tasks: Promise.then, queueMicrotask
// Macro tasks: setTimeout, setInterval, events
console.log('1');
setTimeout(() => console.log('2'), 0); // Macro
Promise.resolve().then(() => console.log('3')); // Micro
console.log('4');
// Order: 1, 4, 3, 2Macro and micro tasks — like queues in a store: some customers are served faster, others wait their turn! 🏪👥
Event Loop — like a cashier in a store: decides who gets served next:
// Event Loop works by simple rules:
// 1. Execute current code
// 2. Check micro tasks
// 3. Check macro tasks
// 4. RepeatMicro tasks — like urgent orders: done right after current task:
// Micro task examples:
// - Promise.then/catch/finally
// - queueMicrotask
// - await (internally uses Promise)
console.log('Start');
// Micro task
Promise.resolve().then(() => console.log('Micro task'));
console.log('End');
// Execution order:
// 1. Start
// 2. End
// 3. Micro taskMacro tasks — like regular shopping: wait your turn:
// Macro task examples:
// - setTimeout/setInterval
// - Click, scroll events
// - XMLHttpRequest (AJAX)
console.log('Start');
// Macro task
setTimeout(() => console.log('Macro task'), 0);
console.log('End');
// Execution order:
// 1. Start
// 2. End
// 3. Macro taskExecution queue — strict hierarchy:
console.log('1');
// Macro task
setTimeout(() => console.log('2'), 0);
// Micro task
Promise.resolve().then(() => console.log('3'));
// Another micro task
Promise.resolve().then(() => console.log('4'));
console.log('5');
// Execution order:
// 1. '1' (regular code)
// 2. '5' (regular code)
// 3. '3' (micro task)
// 4. '4' (micro task)
// 5. '2' (macro task)Priority rules:
// When you need to execute code "right after"
function updateUI() {
// Update interface
element.textContent = 'New text';
// Right after — do additional work
Promise.resolve().then(() => {
// This work executes before any setTimeout
console.log('Additional work');
});
}// When you need to defer execution
function deferWork() {
// Defer until next cycle
setTimeout(() => {
console.log('Deferred work');
}, 0);
}// ❌ Mistake — thinking setTimeout executes first
setTimeout(() => console.log('setTimeout'), 0);
Promise.resolve().then(() => console.log('Promise'));
// Result: Promise, then setTimeout
// ✅ Correct — remember micro tasks come first// ❌ Mistake — not understanding order
console.log('1');
setTimeout(() => console.log('2'), 0);
console.log('3');
Promise.resolve().then(() => console.log('4'));
console.log('5');
// Order: 1, 3, 5, 4, 2
// ✅ Correct — first synchronous, then micro, then macroUnderstanding macro and micro tasks helps write predictable asynchronous code! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪