Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isn't truly asynchronous, non-blocking javascript impossible?

So, am I missing something here?

All javascript engines in popular modern browsers (as of 2011) are single-threaded.

This means while EVENTS can occur asynchronously, they are still queued (in "single-file") to be executed.

This means that all these techniques to load external javascript into an HTML page, they are really only to allow the download to happen asynchronously, the execution of the downloaded code however, always happens one (function) at a time, one file at a time.

So other "tips" I've seen on the web to breakup and execute initializing code blocks using setTimeout, that would be bogus, incorrect advice - the timer is also a single-file queue and executes only in order. With setTimeout you are just causing an out-of-order execution via the timer and allowing other events in the browser (ie. mouse clicks or keypress, etc.) to jump in the queue - that in itself might be good to have, but it's certainly not asynchronous code execution.

If I'm right, there's a bunch of bad, misunderstood advice out there that's too often repeated.

like image 975
ck_ Avatar asked Mar 25 '11 15:03

ck_


2 Answers

Aren't you confusing asynchronicity with concurrency? It's true there isn't any concurrency in the browser JS environment (aside from web workers, and anything the browser does internally, like I/O and rendering), but asynchronicity just means that all calls are non-blocking, and control flow always returns immediately.

Your definitions of 'blocking'/'non-blocking' aren't clear either. The wide-spread meaning of a blocking function call is that it doesn't return control to the caller until all computation, I/O, etc. has completed. This says nothing about concurrency.

like image 136
pmdj Avatar answered Sep 30 '22 12:09

pmdj


AFAIK, Javascript is asynchronous in the sense that, although it runs on one thread, said thread is running concurrently to other threads executing other actions (page rendering, for instance) independently of the Javascript engine.

The definition, I think, does not mean to state that the Javacsript itself can be executed in any order - that's linear and in accordance with scope.

like image 20
Grant Thomas Avatar answered Sep 30 '22 13:09

Grant Thomas