How does javaScript work?

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?


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 comment

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 compile, 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.


    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 comes 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 comes, 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).


    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 just 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 communicate 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 (eg 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

    链接地址: http://www.djcxy.com/p/79394.html

    上一篇: Python使用多处理

    下一篇: javaScript如何工作?