Is JavaScript Guaranteed to Be Single-Threaded

Is JavaScript guaranteed to be single-threaded?

That's a good question. I'd love to say “yes”. I can't.

JavaScript is usually considered to have a single thread of execution visible to scripts(*), so that when your inline script, event listener or timeout is entered, you remain completely in control until you return from the end of your block or function.

(*: ignoring the question of whether browsers really implement their JS engines using one OS-thread, or whether other limited threads-of-execution are introduced by WebWorkers.)

However, in reality this isn't quite true, in sneaky nasty ways.

The most common case is immediate events. Browsers will fire these right away when your code does something to cause them:

var l= document.getElementById('log');

var i= document.getElementById('inp');

i.onblur= function() {

l.value+= 'blur\n';

};

setTimeout(function() {

l.value+= 'log in\n';

l.focus();

l.value+= 'log out\n';

}, 100);

i.focus();
<textarea id="log" rows="20" cols="40"></textarea>

<input id="inp">

Is JavaScript single threaded?

Javascript isn't inherently single-threaded or multi-threaded as a language. There are Javsacript environments that don't offer Javascript threads and environments that do offer Javascript threads. The language itself doesn't specify single-threadedness or multi-threadedness. Instead, it's up to the environment whether it wants to make threads of Javascript available.

So, to your specific question:

Is JavaScript single threaded?

No. It's not specifically single threaded or multiple threaded. The language specification doesn't require either. The threading of Javascript is up to the run-time environment to implement. It so happens that both the browser and node.js started out without Javascript threads and an event-driven architecture which led to this notion that there are no threads in a Javascript environment, but there ARE. They now both offer Javascript threads (WebWorkers in the browser and WorkerThreads in node.js).

The Javascript specification offers some features that are useful in multi-threaded environments such as SharedArrayBuffer objects and Atomics and environments that offer threading provide additional libraries. So, the current language specification recognizes some of the needs of multi-threading and provides some tools for it, though there is no specific requirement that a Javascript runtime has or doesn't have threads. It's up to the run-time whether they want to offer that capability to run multiple Javascript threads of execution in parallel or not.

Java Script is a single threded then how it can have fetch or other libraries to make async request

Javascript runs on a core which is single threaded and its also a event driven language that make all request into events,
application running in node js runs asynchronously using node event loop and event loop where looks upon the events and process them asynchronously.

So the request you make taken by events and processed asynchronously.

Is javascript single-threaded?

is it guaranteed to be always single-threaded on all browsers?

Yes.

Of course, things like HTTP requests might work in different threads behind the scenes, but when your Javascript code is executed it can only happen from one thread at a time.

How is Javascript single threaded?

JavaScript (in browsers) doesn't run concurrently2.

At most one of the setTimeout callbacks can execute at a time - as there is one JavaScript execution context or "thread".

However, the "next scheduled timeout" to run is always run .. next. The "4" runs before the "2" callback because it was scheduled to run sooner. The timeouts were effectively scheduled from the same time (none of the operations were blocking), but "2" had a much longer interval.

The underlying implementation may use threads1 - but JavaScript in the same global context doesn't run concurrently and guarantees consistent and atomic behavior between all callbacks.


1 Or it may not; this can be handled without any threads in a select/poll implementation.

2 In the same context: i.e. Tab/Window, WebWorker, host Browser Control. For example, while WebWorkers are run concurrently they do so in different contexts and follow the same asynchronous model (eg. as used by timers).

Is promise.all useful given that javascript is executed in a single thread?

First of all - JavaScript as a language does not say anything about concurrency. In fact, in a lot of scenarios you can create and run multithreaded JavaScript - WebWorkers in the web, in node, and when integrating a JS engine in an existing app yourself.

In fact, there is nothing asynchronous in the JavaScript language (Until ES2015). However, in practice - host environments which are how JavaScript interacts with the world implement asynchronous APIs.

While execution of JavaScript DOM code is single threaded, I/O operations actually run on a different thread and events notify the JavaScript thread of changes. Sometimes, using an operating system facility for asynchronous concurrency completely like IOCP (I/O completion ports) in Windows.

Let's take AJAX for example. Let's say I have a list of URLs and I map each of them to an XHR call.

// with all
var a = ["url1","url2","url3"].map(makeAjaxPromise); // make 3 ajax calls
Promise.all(a).spread(function(res1,res2,res3){ // Q.all with Q
alert("Everything loaded!");
});

Here, 3 ajax calls are made at once. Even though JavaScript runs in a single thread in this case - the requests are all made in parallel, and the thread gets notified once they are complete using an "event loop" that notifies code when events completed which in turn resolves the promises.

However, when you do

 makeAjaxPromise("url1").
then(makeAjaxPromise.bind(null,"url2").
then(makeAjaxPromise.bind(null,"url3").then(function(){
alert("Everything loaded!"); // disregarding getting the data here
});

It'll make a single request, wait for it to complete, make another one, wait for it, make a third one only then and only then resolve.

So - first case:

  • JavaScript thread makes 3 DOM API calls
  • DOM API gets these calls and makes XHR requests, it yields control back to JavaScript immediately
  • When those requests are ready, it notifies JavaScript and it runs the handler if it is free to do so.

Second case

  • JavaScript thread makes a DOM API call.
  • DOM API gets call, makes an XHR request, yields control back to JavaScript.
  • When the first request is ready, JavaScript gets notified and it runs the next in line:
    -JavaScript thread makes a DOM API call.
  • DOM API gets call, makes an XHR request, yields control back to JavaScript.
  • When the second request is ready, JavaScript gets notified and it runs the next in line:
    -JavaScript thread makes a DOM API call.
  • DOM API gets call, makes an XHR request, yields control back to JavaScript.
  • When the thirdrequest is ready, JavaScript gets notified and it runs the next in line:
  • All three ready.

So in the second case, the requests are not made in parallel and JavaScript has to wait a lot more, possibly three times as much.

Since JavaScript is single-threaded, how are web workers in HTML5 doing multi-threading?

As several comments have already pointed out, Workers really are multi-threaded.

Some points which may help clarify your thinking:

  • JavaScript is a language, it doesn't define a threading model, it's not necessarily single threaded
  • Most browsers have historically been single threaded (though that is changing rapidly: IE, Chrome, Firefox), and most JavaScript implementations occur in browsers
  • Web Workers are not part of JavaScript, they are a browser feature which can be accessed through JavaScript

Are browsers still single-thread?

Technically yes they are still all running single threads in the treatment of generating your page and actions on the front end. There are ways to make it seem like it isn't and run a javascript process independently like a pseudo multi thread using web workers introduced in html5. By pseudo I mean it works like most multi threaded processes it switches so fast between the clock interrupts it seems as if it's multi threaded. More information on web workers can be found at http://www.w3schools.com/html/html5_webworkers.asp as well as google of course.



Related Topics



Leave a reply



Submit