Non-Blocking

How does JavaScript manage to be so efficient with asynchronous code if it only has one thread? The answer lies in the Event Loop—a single-threaded, non-blocking, event-driven execution model.

Blocking vs Non-Blocking

In traditional synchronous languages (like Python or PHP), functions like “sleep” or “wait” actually halt the entire program.

# Python Example (Blocking)
import time

print("Start")
time.sleep(4) # The entire program freezes for 4 seconds
print("End")

JavaScript’s main thread cannot be blocked this way. Instead of freezing, JavaScript delegates waiting periods to the background using callbacks.

// JavaScript Example (Non-Blocking)
console.log("Start");

setTimeout(() => {
  console.log("End"); // Runs after 4 seconds
}, 4000);

console.log("Middle");

// Output:
// Start
// Middle
// End

How Delegation Works

When JavaScript encounters setTimeout, it basically says:

“Hey, I know I can’t block the program right now, but please take this callback function and run it for me in 4 seconds.”

The main thread instantly moves on to print “Middle”. It is always available to do work, and waiting is delegated “for later.”