Discover how Node.js keeps your app lightning fast by juggling tasks behind the scenes!
Why Event loop mental model in Node.js? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a busy kitchen where you must cook many dishes at once, but you only have one stove and one chef. You try to cook each dish one by one, waiting for each to finish before starting the next.
This manual way makes the kitchen slow and inefficient. If one dish takes a long time, everything else waits, causing delays and unhappy guests. It's hard to keep track of what's cooking and when to start the next dish.
The event loop acts like a smart kitchen manager who keeps track of all tasks and starts new ones as soon as the stove is free. It lets Node.js handle many tasks without waiting for each to finish, making everything faster and smoother.
function task() { heavyWork(); console.log('Done'); } task(); task();setTimeout(() => console.log('Done'), 0); setTimeout(() => console.log('Done'), 0);
This mental model enables writing fast, non-blocking programs that handle many things at once without freezing or slowing down.
Think of a web server handling thousands of users clicking buttons and loading pages simultaneously without waiting for one request to finish before starting another.
Manual sequential tasks cause delays and inefficiency.
The event loop manages tasks smartly to keep things moving.
This model helps build fast, responsive applications.
Practice
Promise callbacks before timers?Solution
Step 1: Understand event loop phases
The event loop has phases: timers, I/O callbacks, idle, poll, check, close callbacks, and microtasks run between phases.Step 2: Identify when Promise callbacks run
Promise callbacks are microtasks and run immediately after the current operation, before timers and I/O callbacks.Final Answer:
Microtasks queue -> Option CQuick Check:
Promises run in microtasks before timers [OK]
- Thinking timers run before promises
- Confusing I/O callbacks with microtasks
- Assuming check phase runs before microtasks
Solution
Step 1: Identify function to run after delay
setTimeoutschedules a function after a specified delay in milliseconds.Step 2: Check syntax for zero delay
UsingsetTimeout(myFunc, 0)runsmyFuncafter the current call stack is empty, effectively scheduling it soon.Final Answer:
setTimeout(myFunc, 0); -> Option AQuick Check:
setTimeout with 0 delay schedules function correctly [OK]
- Using setInterval for one-time delay
- Passing extra argument to setImmediate
- Confusing process.nextTick with setTimeout syntax
console.log('start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('end');Solution
Step 1: Identify synchronous and asynchronous parts
console.log('start')andconsole.log('end')run immediately (synchronously).setTimeoutcallback runs later. Promise callback runs as microtask after current stack.Step 2: Trace execution order
Output order: 'start' (sync), 'end' (sync), 'promise' (microtask), 'timeout' (timer callback).Final Answer:
start
end
promise
timeout -> Option DQuick Check:
Synchronous > microtasks > timers [OK]
- Thinking promise runs after timeout
- Mixing order of synchronous logs
- Assuming setTimeout runs immediately
setTimeout(() => console.log('timeout'));
process.nextTick(() => console.log('nextTick'));
Promise.resolve().then(() => console.log('promise'));Which line causes the earliest callback to run, and why might the output order be unexpected?
Solution
Step 1: Understand callback priorities
process.nextTickcallbacks run immediately after the current operation, before promise microtasks and timers.Step 2: Explain output order
Even though promises are microtasks,process.nextTickcallbacks have higher priority and run first, which can surprise learners expecting promises first.Final Answer:
process.nextTick runs earliest because it runs before microtasks -> Option AQuick Check:
nextTick > promises > timers [OK]
- Assuming timers run before nextTick
- Confusing promise and nextTick order
- Thinking callbacks run simultaneously
Solution
Step 1: Understand event loop blocking
Running a heavy task synchronously blocks the event loop, making the app unresponsive.Step 2: Choose non-blocking approach
Splitting the task into smaller chunks withsetTimeoutallows the event loop to process other events between chunks, keeping responsiveness.Final Answer:
Use setTimeout to split the task into smaller chunks -> Option BQuick Check:
Split heavy tasks with timers to avoid blocking [OK]
- Running heavy tasks synchronously
- Using nextTick for long tasks (blocks event loop)
- Assuming promises alone prevent blocking
