Isn't truly asynchronous, non-blocking javascr

2020-05-28 11:04发布

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.

7条回答
劫难
2楼-- · 2020-05-28 11:42

I'm no javascript guru, so this is just my musing, but it would appear to me that you might be partially right.

However, if you think of the Javascript thread as "time" and allow other functions to jump in the flow of time wherever you need them, then it makes javascript essentially act like a non-blocking process.

On the other hand, HTML 5 defines web workers, which (if I'm understanding it correctly), IS "multi-threaded," in the sense that many can be processing at the same time.

查看更多
登录 后发表回答