We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Non Blocking

So how does JavaScript manage to be so efficient with asynchronous code? The answer is the event loop.

The event loop is a single-threaded, non-blocking, event-driven, asynchronous execution model.

Say that five times fast.

We already covered the single-threaded part, now let's grok non-blocking. Let's use this Python code as an example:

import time

print("Start")
time.sleep(2)
print("Middle")
time.sleep(2)
print("End")

This code prints "Start", then waits for 2 seconds, prints "Middle", waits another 2 seconds, and finally prints "End". The time.sleep(2) function calls are blocking: they stop the program's execution until 2 seconds have passed.

Let's write a similar example in JavaScript:

console.log("Start");
setTimeout(() => {
  console.log("End");
}, 4000);
console.log("Middle");

This code prints "Start", then "Middle" immediately, waits 4 seconds, then prints "End". The main thread in JavaScript cannot be blocked. That's why setTimeout takes a callback function as an argument, it basically says:

Hey, I know I can't block the program, but please Mr. JavaScript engine, can you take this function and run it for me in 4 seconds?

So, the main thread should always be available to do work, and blocking (read: waiting) is delegated "for later".

Assignment

A Go developer joined the Textio team and thought setTimeout would block execution like time.Sleep() in Go. It's possible, but slightly more complicated.

To await the result of sleep, the caller must be an async function.

The sleep helper function is a JavaScript staple.