Why not to block the event loop?
What the Event Loop is
The Event Loop is a mechanism that:
- sequentially runs tasks (callbacks, promises, timers, events);
- handles asynchronous operations;
- is responsible for the interface's responsiveness and the app's responsiveness.
JS is a single-threaded language: at any moment, only one instruction executes. If something takes a long time, everything else sits in the queue and waits.
What "blocking the Event Loop" means
Blocking the Event Loop is a situation where JS runs a long synchronous operation (for example, a computation, an infinite loop, a synchronous file read, etc.), and until it finishes, other events are not processed.
Example:
console.log("Start");
for (let i = 0; i < 1e9; i++) {} // blocks the Event Loop
console.log("End");While this loop is running:
- the browser does not respond to clicks, scrolling, input;
- timers and promises do not run;
- the UI "hangs".
Why this is bad
1. The interface freezes
The user cannot interact with the site: buttons, input fields, animations - everything is "frozen".
2. Asynchronous operations do not run
Neither setTimeout, fetch, nor Promise.then will start until the blockage ends.
setTimeout(() => console.log("1s has passed"), 1000);
while (Date.now() < Date.now() + 5000) {} // blocks for 5 secResult:
(after 5 seconds) 1s has passedThe timer fired late.
3. Loss of performance in Node.js
If a CPU-heavy task runs on a Node.js server (for example, parsing a large JSON, encryption, etc.), the remaining requests pile up in a queue - the server stops responding.
How to avoid blocking
- Split computations into chunks (chunking):
function heavyTask() {
let i = 0;
function step() {
while (i < 1e9 && i % 1e5 !== 0) i++;
if (i < 1e9) setTimeout(step); // hand control back to the Event Loop
}
step();
}- Use Web Workers (in the browser) For heavy computations, run the code in a separate thread so it does not interfere with the main one.
- In Node.js, use Worker Threads or child_process
import { Worker } from 'worker_threads';
new Worker('./heavy-task.js');- Don't use synchronous I/O methods:
fs.readFileSync- nofs.readFile- yescrypto.pbkdf2Sync- nocrypto.pbkdf2- yes
In short
| Reason | What happens |
|---|---|
| JS is single-threaded | Everything runs in one thread |
| Blocking code | Delays the Event Loop |
| The UI stops responding | The interface "freezes" |
| The server "hangs" | Requests are not processed |
| Solution | Asynchrony, chunking, workers |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.