Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is JavaScript multithreaded?

Here's my issue - I need to dynamically download several scripts using jQuery.getScript() and execute certain JavaScript code after all the scripts were loaded, so my plan was to do something like this:

function GetScripts(scripts, callback) {   var len = scripts.length   for (var i in scripts)   {     jQuery.getScript(scripts[i], function()      {       len --;       // executing callback function if this is the last script that loaded       if (len == 0)         callback()       })   } } 

This will only work reliably if we assume that script.onload events for each script fire and execute sequentially and synchronously, so there would never be a situation when two or more of the event handlers would pass check for (len == 0) and execute callback method.

So my question - is that assumption correct and if not, what's the way to achieve what I am trying to do?

like image 707
Andrey Avatar asked Nov 02 '09 19:11

Andrey


People also ask

Can JavaScript do multithreading?

Running JavaScript on GraalVM supports multithreading. Depending on the usage scenario, threads can be used to execute parallel JavaScript code using multiple Context objects, or multiple Worker threads.

Is JavaScript async multithreaded?

JavaScript is a single-threaded language and, at the same time, also non-blocking, asynchronous and concurrent. This article will explain to you how it happens.

Is JavaScript multithreaded and how it handles multithreading?

As you may probably know, Javascript is single-threaded. To clarify better, this means that one single thread handles the event loop. For older browsers, the whole browser shared one single thread between all the tabs.

Why JavaScript is a single threaded language?

Q: Ok, is Javascript single-threaded? A: Yes, Javascript “runtime” is single-threaded. It executes the javascript program. It maintains a single stack where the instructions are pushed to control the order of execution and popped to get executed.


2 Answers

No, JavaScript is not multi-threaded. It is event driven and your assumption of the events firing sequentially (assuming they load sequentially) is what you will see. Your current implementation appears correct. I believe jQuery's .getScript() injects a new <script> tag, which should also force them to load in the correct order.

like image 59
gnarf Avatar answered Sep 19 '22 11:09

gnarf


Currently JavaScript is not multithreaded, but the things will change in near future. There is a new thing in HTML5 called Worker. It allows you to do some job in background.

But it's currently is not supported by all browsers.

like image 36
Ivan Nevostruev Avatar answered Sep 21 '22 11:09

Ivan Nevostruev