fuzzybabybunny
fuzzybabybunny

Reputation: 5254

How is JS both non-blocking / asynchronous but single-threaded?

I'm having trouble visualizing how Javascript can be both single-threaded but non-blocking on the client. I've always envisioned something like an assembly line:

This is how I envisioned non-blocking, async code. The main thread of Line 1 gets to continue to chug along without having to wait for Line 2 to finish first. But this assembly line metaphor requires two assembly lines, or two threads, but JS is single-threaded.

So now I'm confused.

Upvotes: 2

Views: 151

Answers (2)

Bergi
Bergi

Reputation: 664195

No, a thread is not an assembly line. To keep your metaphor:

  • an assembly line is sequence of things that need to be done to your automobile (or whatever things the line is producing)
  • a thread is like a workman who is working on these assembly lines

Yes, in a single-threaded environment (one-man factory) the worker can only work in one assembly line at a time. But that doesn't mean the assembly lines cannot be run concurrently. The worker can start a machine that paints the car, then go over to the other line and install a part of the motor, then go back to the now painted car and start drying it…

That's how JS works. The worker has to finish his current step before he can work on the next task, but then he can choose another assembly line as he sees it fitting. And this even allows parallel processing when all he needs to do is start a machine that does some work in the background, as he then is available to do other things while waiting for a signal that the machine has finished.

Upvotes: 1

Shilly
Shilly

Reputation: 8589

In short, the runtime has an event loop that kinda simulates async in 1 thread. In long, I found this video and text to be a good explanation: http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html

Upvotes: 5

Related Questions