JavaScript Blocking vs Non-Blocking
JavaScript is single-threaded, so it usually does one thing at a time. Depending on how the code is written, it can either block the program or let other tasks keep running.
1. What is a blocking code?
Blocking code is code that stops everything else from running until it's finished.
When JavaScript hits a blocking task, it just sit there and does nothing else.
Code Example – Blocking
console.log("Start");
for (let i = 0; i < 10000; i++) {
// heavy loop
}
console.log("End");
What happens here?
- "Start" prints
- The loop runs (this takes time)
- Nothing else can run during the loop
- "End" prints only after the loop finishes
This is called blocking, because it blocks the main thread.
2. What is Non-Blocking Code?
Non-blocking code allows JavaScript to continue running other tasks while waiting for something to finish.
This is usually done using:
- setTimeout
- Promises
- async/await
- APIs (like fetch)
Example of Non-Blocking Code
console.log("Start");setTimeout(() => {console.log("This is async (non-blocking)");}, 2000);console.log("End");
What happens here?
- "Start" prints
-
setTimeoutstarts timer but does NOT stop code - "End" prints immediately
- After 2 seconds → async message prints
JavaScript keeps running instead of waiting.
