Node.js › Event Loop & Non-blocking IO
How does the event loop handle a large synchronous loop (like processing a huge array with a for loop), and what problem does this cause?
IntermediateAnswer
A synchronous for loop, no matter how large, runs to completion entirely within a single pass of the event loop, without yielding control back at any point -- during that entire time, the event loop cannot process any other pending callbacks, timers, or incoming I/O events, meaning every other concurrent request or scheduled task is completely blocked and delayed until the loop finishes, regardless of how many CPU cores the machine has.
// This blocks the event loop entirely until the loop completes
for (let i = 0; i < 100000000; i++) {
result += computeExpensiveValue(i);
}
// No other request can be handled by this process during this entire loopReal-world example A single API request that accidentally triggered a synchronous loop processing millions of records caused every other concurrent user's request to that same server instance to hang until the loop finished, illustrating why CPU-bound work needs to either be chunked, moved to a worker thread, or handled differently entirely.