The event loop helps Node.js handle many tasks without waiting for each to finish. It keeps your app fast and responsive.
Event loop mental model in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
Node.js runs JavaScript code in a single thread. The event loop checks for tasks to run and executes them one by one. It handles callbacks from timers, I/O, and promises.
The event loop runs continuously while your program is active.
It uses queues to manage different types of tasks.
Examples
Node.js
setTimeout(() => {
console.log('Timer done');
}, 1000);
console.log('Start');Node.js
console.log('First'); process.nextTick(() => { console.log('Next Tick'); }); console.log('Last');
Node.js
Promise.resolve().then(() => {
console.log('Promise resolved');
});
console.log('After promise');Sample Program
This program shows the event loop order: synchronous code runs first, then promise callbacks, then timer callbacks.
Node.js
console.log('Start'); setTimeout(() => { console.log('Timeout callback'); }, 0); Promise.resolve().then(() => { console.log('Promise callback'); }); console.log('End');
Important Notes
The event loop lets Node.js do many things without waiting for each to finish.
Microtasks like promises run before timers in the event loop.
Understanding the event loop helps avoid bugs with timing and order of code execution.
Summary
The event loop runs tasks in order to keep Node.js fast and non-blocking.
Synchronous code runs first, then microtasks like promises, then timers and I/O callbacks.
Knowing this helps you write better asynchronous code.
Practice
1. Which part of the Node.js event loop runs
Promise callbacks before timers?easy
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]
Hint: Remember: promises run before timers in microtasks [OK]
Common Mistakes:
- Thinking timers run before promises
- Confusing I/O callbacks with microtasks
- Assuming check phase runs before microtasks
2. Which of the following is the correct syntax to schedule a function to run after 0 milliseconds in Node.js?
easy
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]
Hint: Use setTimeout(func, 0) to schedule next tick [OK]
Common Mistakes:
- Using setInterval for one-time delay
- Passing extra argument to setImmediate
- Confusing process.nextTick with setTimeout syntax
3. What will be the output order of the following code?
console.log('start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('end');medium
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]
Hint: Sync logs first, then promises, then timers [OK]
Common Mistakes:
- Thinking promise runs after timeout
- Mixing order of synchronous logs
- Assuming setTimeout runs immediately
4. Consider this code snippet:
Which line causes the earliest callback to run, and why might the output order be unexpected?
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?
medium
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]
Hint: nextTick runs before promises and timers [OK]
Common Mistakes:
- Assuming timers run before nextTick
- Confusing promise and nextTick order
- Thinking callbacks run simultaneously
5. You want to run a CPU-heavy task without blocking the event loop in Node.js. Which approach best uses the event loop model to keep your app responsive?
hard
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]
Hint: Split heavy tasks with setTimeout to avoid blocking [OK]
Common Mistakes:
- Running heavy tasks synchronously
- Using nextTick for long tasks (blocks event loop)
- Assuming promises alone prevent blocking
