Skip to main content

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:

javascript
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.

javascript
setTimeout(() => console.log("1s has passed"), 1000); while (Date.now() < Date.now() + 5000) {} // blocks for 5 sec

Result:

javascript
(after 5 seconds) 1s has passed

The 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

  1. Split computations into chunks (chunking):
javascript
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(); }
  1. 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.
  2. In Node.js, use Worker Threads or child_process
javascript
import { Worker } from 'worker_threads'; new Worker('./heavy-task.js');
  1. Don't use synchronous I/O methods:
  • fs.readFileSync - no
  • fs.readFile - yes
  • crypto.pbkdf2Sync - no
  • crypto.pbkdf2 - yes

In short

ReasonWhat happens
JS is single-threadedEverything runs in one thread
Blocking codeDelays the Event Loop
The UI stops respondingThe interface "freezes"
The server "hangs"Requests are not processed
SolutionAsynchrony, chunking, workers

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.