Event Loop
suggest changeBlocking Operation Example
const loop = (i, max) => {
while (i < max) i++;
return i;
};
// This operation will block Node.js
// Because, it's CPU-bound
// You should be careful about this kind of code
loop(0, 1e8);
Non-Blocking IO Operation Example
console.log('start');
setImmediate(() => {
console.log('next event-loop iteration');
});
console.log('scheduled');
start
scheduled
next event-loop iteration
The event loop runs JavaScript callbacks on one thread. A long CPU-bound callback prevents other callbacks from running. Asynchronous I/O can progress through the operating system or libuv while JavaScript is waiting, and its completion callback runs on a later event-loop iteration.
However, Node.js under the carpet uses multi-threading for some of its operations through libuv Library.
Performance Considerations
- Non-blocking operations return control to the event loop while work is pending.
- Long CPU-bound operations block the event loop. Move substantial CPU work to worker threads or another process.
Node.js performs non-blocking I/O through operating-system facilities and libuv's worker pool. When an operation completes, Node.js schedules its callback.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents