最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

multithreading - How does multi-threading or async code in JavaScript work? - Stack Overflow

programmeradmin6浏览0评论

I am no beginner in javascript. I am actually working on this for past 3-4 months but today I read this statement about "What is JavaScript?"

JavaScript is single-threaded, non-blocking, asynchronous, concurrent language.

and I was lost. If JavaScript is single-threaded, how can it be concurrent and how can it be asynchronous because you need to keep track what your async code is doing and without another thread, it is impossible to track 2 or more code at a same time?

I am no beginner in javascript. I am actually working on this for past 3-4 months but today I read this statement about "What is JavaScript?"

JavaScript is single-threaded, non-blocking, asynchronous, concurrent language.

and I was lost. If JavaScript is single-threaded, how can it be concurrent and how can it be asynchronous because you need to keep track what your async code is doing and without another thread, it is impossible to track 2 or more code at a same time?

Share Improve this question edited Jul 28, 2020 at 21:02 NiRUS 4,2692 gold badges31 silver badges51 bronze badges asked Mar 26, 2016 at 8:04 Ajay GaurAjay Gaur 5,2807 gold badges40 silver badges63 bronze badges 2
  • 2 You are thinking about parallel execution, which is not the same as concurrent execution: stackoverflow./questions/1897993/… – Sverri M. Olsen Commented Mar 26, 2016 at 8:15
  • 1 "and how can it be asynchronous because you need to keep track what your async code is doing and without another thread" --- the simple explanation is: the userland of the language is single threaded, but the runtime/environment that hosts it is multithreaded under the hood. Browsers have theadpools to do routine background jobs, nodejs also has one. – zerkms Commented Mar 26, 2016 at 13:06
Add a ment  | 

3 Answers 3

Reset to default 8

Ah.. here's the thing:

JavaScript is single threaded, but it has a lot of spare time on its hands.

When it is waiting for something to load out off the network, or its waiting for something off disk or waiting for the OS to hand something back to it, it can run other code.

setTimeout(function() {
  // Do something later.
}, 1000);

While it is waiting for that timeout to return an execute that code, it can run code from OTHER timeouts, or network calls or any other async code in the system. It only runs ONE block of code at a time, however, which is why we say it is single threaded.

That thread can just bounce around. A lot.

And, as others have said, there are web workers and service workers, but those run VERY isolated from your main thread. They can't change values behind your main thread's back.

Updated per ment

The event loop works by:

  • Waiting for an event
  • Handling that event.

JavaScript is, indeed, blocked while handling an event. While code is running, nothing else in that page (assuming browser main thread) can run.

It isn't a literal event loop as you would have in C or C++, not as far as the JS is concerned. It's just events waiting to happen.

/// Sample code
document.addEventListener("click", function() { /* Handle click */ });

window.addEventListener("load", function() { /* handle load */ });

In this case, have two event listeners in our code. The JS engine will pile, then execute those two statements. Then, for all intents, "sleep" while waiting for something to happen. In reality, that same thread may handle various house-keeping tasks like drawing the HTML page, listening for move movements and emiting all sorts of events, but that doesn't matter for this discussion.

Then, once the rest of the page is loaded, the browser will emit a load event, which will be caught the listener and some more code will be run.

Then it will go back to idling until someone clicks on the document, then more code will run.

If we change the code to this:

document.addEventListener("click", function() {
  while(true);
});

then when someone clicks on the document, our thread will go into an endless loop and all browser activity in that window will cease. Might even freeze the entire browser, depending in which one you are running.

Eventually, the browser will give a chance to kill that task so you can have your system back.

Latest Update

If you are aware of Webassembly there is a proposal in place for Threads via natively piled modules

pthreads-style read this git issue tracker link(1073)


In continuation with @Jeremy J Starcher answer.

Javascript is always been single threaded runtime using asynchronous, non-blocking and event-driven models of execution.

To know more about event loop execution in JS i highly remend you to watch this Youtube video. Simply superb explanation by Philip Roberts.

Good olden days, developers would beat around the bush to achieve similar to thread model using

  • setTimeout with 0 - milliseconds or setIntervals : Basically instructing the engine to take up non-trivial tasks when the engine goes idle or wait mode during a http request or execute the code by switching back and forth in intervals kinda round-robin fashion.
  • Hidden Iframe : Run a JS code in a sandbox with a bridge to municate from parent to iframe and vice versa. Technically Iframe doesn't run on separate thread but gets things done as a fake thread.

Fast forwarding [ >>> ] to Multi-threading models by ECMA:

Off late things have changed with the requirement to spawn a thread in JS engines to offload few smaller logical tasks or a network proxy task to a separate thread and concentrate on UI driven tasks like presentation and interaction layer on main thread, which makes sense.

With that requirement in mind ECMA came up with two model/API basically to solve this.

1. Web Worker: (SIC - Mozilla)

Web Workers makes it possible to run a script operation in background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.

[ WebWorker can be split into two ]

  • Shared Worker

The SharedWorker interface represents a specific kind of worker that can be accessed from several browsing contexts, such as several windows, iframes or even workers. They implement an interface different than dedicated workers and have a different global scope, SharedWorkerGlobalScope.

  • Dedicated Worker : Same as Webworker, created using Worker() API but uses DedicatedWorkerGlobalScope

Worker is an object created using a constructor (e.g. Worker()) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. This context is represented by a DedicatedWorkerGlobalScope object in the case of dedicated workers


2. Service Worker (SIC - Mozilla)

Service workers essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.

One example usage would be in PWA - Progressive web app to download scripts, lazy loading purposes of assets.


Read this article by Eric Bidelman on HTML5Rocks good explanation about the code itself and implementation

JavaScript may be "single-threaded" (I'm not sure this is really the case), but you can use/create webworkers to run javascript outside the main thread.

So you can run two pieces of code at the same time in parallel.

I think it is wrong to say that a language is this or that when what we really mean is that our programs are this or that.

For example: NodeJS is single-threaded and can run code asynchronous because it uses an event-driven behaviour. (Something es up and fires an event... Node deals with it and if it is something like an online request, it does other things instead of waiting for the response... when the response es, it fires an event and Node captures it and does whatever needs to be done).

So Javascript is...
single-threaded? No, as you can use WebWorkers as a second thread
non-blocking? You can write code that blocks the main thread. Just build a for that executes a hundred million times or don't use callbacks.
asynchronous? No, unless you use callbacks.
concurrent? Yes, if you use webworkers, callbacks or promises (which are really callbacks).

发布评论

评论列表(0)

  1. 暂无评论